This is C. You can't just call printf() and expect it to do the work for you. You need to iterate through the array with a for() or while() loop and print out each element.

Assuming it is an array of strings:

int i;
for (i=0; i<size; i++)
    printf("array[%d] = %s\n", i, array[i]);
Answer from Jonathon Reinhart on Stack Overflow
๐ŸŒ
IncludeHelp
includehelp.com โ€บ code-snippets โ€บ declare-and-print-dynamic-array-using-c-pointer.aspx
C - Declare and Print Dynamic Array using C Pointer - IncludeHelp
August 3, 2016 - //C - Declare and Print Dynamic Array using C Pointer. #include <stdio.h> #include <stdlib.h> int main(){ int *ptr,i; ptr=(int*)malloc(5*sizeof(int)); if(ptr==NULL){ printf("Error in allocating memory!!!"); return -1; } *(ptr+0)=10; *(ptr+1)=20; *(ptr+2)=30; *(ptr+3)=40; *(ptr+4)=50; printf("Array elements are:\n"); for(i=0;i<5;i++){ printf("%d ",*(ptr+i)); } return 0; }
Discussions

Initializing and printing an array using pointers and dynamic allocation in C - Code Review Stack Exchange
I have written a code for basic array creation and printing it's values in C. I would appreciate comments on how it can be improved, and the industry standards. One issue I'm encountering is havi... More on codereview.stackexchange.com
๐ŸŒ codereview.stackexchange.com
January 29, 2015
c - dynamic array allocation and printing the elements - Stack Overflow
Connect and share knowledge within a single location that is structured and easy to search. Learn more about Teams ยท Get early access and see previews of new features. Learn more about Labs ... t=(int*)malloc(sizeof(int)); do { printf("enter the element"); scanf("%d",&n); *a=n; printf("%d",a[i]); a=(int*)realloc(t,sizeof(int)); i++; } while(i<4); I am not able to print the elements of dynamic array ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
C - how are dynamic arrays printed? - Stack Overflow
The way you are printing the values is okay. Just don't exceed the size of the array. ... There isn't a way to "check the size" of a dynamic array. You had to specify a size when you allocated it; it's up to you to keep track of that size for as long as you need it. And the values aren't actually random โ€” the computer isn't rolling dice to produce them. They're just whatever bytes happen to be in ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
c - Dynamic Array printing - Stack Overflow
Connect and share knowledge within a single location that is structured and easy to search. Learn more about Teams ... I am trying to print a dynamic array, but I am having trouble with the bounds for the array. For a simple example, lets say I'm trying to loop through an array of ints. More on stackoverflow.com
๐ŸŒ stackoverflow.com
March 24, 2011
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ c-program-to-dynamically-make-array-and-print-elements-sum
C program to dynamically make array and print elements sum
So, if the input is like n = 6, and array elements 9, 8, 7, 2, 4, 3, then the output will be 33 because sum of 9 + 8 + 7 + 2 + 4 + 3 = 33. ... #include <stdio.h> #include <stdlib.h> int main(){ int *arr; int n; int sum = 0; scanf("%d", &n); arr = (int*) malloc(n*sizeof(int)); for(int i = 0; i < n; i++){ scanf("%d", (arr+i)); } for(int i = 0; i < n; i++){ sum += arr[i]; } printf("%d", sum); }
Top answer
1 of 3
18

There are a number of things I would change here, so I'm going to go through the process incrementally, applying changes to the whole file in passes rather than in chunks. I think this should make it more clear why the changes are implemented.


C99 Note

You should have access to, at the very least, a C99 compiler. If that's not true, you can ignore this first point, but if it is, you should change your counter declarations to be inside the first for clause.

for (int i=0;i<n;i++)

Pointers

In initArr, you both return the int array and assign it to the provided out parameter, arr. Why? Out parameters make code confusing and hard to follow! They make sense if you're performing the array allocation somewhere else, but since you're performing the array allocation inside initArr, just drop the arr parameter and return the value.

As a side effect of this, since you no longer need a double pointer, you can replace your dereferences with simple array accesses.

int * initArr (int n)
{
    int * arr = (int *) malloc(sizeof(int*)*n);
    printf("size is %d\n", sizeof(arr));
    for (int i=0;i<n;i++)
    {
        arr[i]=i+10;
    }
    return arr;
}

Next, why are you passing a double pointer (int**) to printArr? More importantly, why does printArr have a return value if it's a purely side-effectful function? Change the parameter to int* and make the function return void.

void printArr (int * arr, int n)
{
    for (int i=0;i<n;i++)
    {
        printf("Arr element %d is %d\n", i, arr[i]);
    }
}

This also simplifies the main function.

int main(void) {
    int * arr2 = initArr(10);
    printArr(arr2,10);

    return 0;
}

Next, let's take a look at the allocation itself (the one in initArr). First of all, you cast to (int *) manually, which is unnecessary and downright discouraged in C. If you're using C++, it's necessary (though you shouldn't need malloc in C++, anyway), but with a C compiler, just drop it.

Second of all, you are not actually allocating the right data! You're allocating n slots for int* valuesโ€”int pointers. You actually want int data. This might not matter depending on your architecture and compiler, but it's still poor code. Fortunately, you can actually fool-proof thisโ€”don't pass an explicit type of sizeof at all! Just deference arr itself, and the compiler will calculate that value's size.

Those changes simplify the allocation to this:

int * arr = malloc(sizeof(*arr)*n);

Finally, the line just after thatโ€”the printf lineโ€”is useless. It will always print the same value because it's checking the size of a pointer, which is always the same size regardless of type (though it can change on different architectures). That said, the line doesn't make any sense there. A function called initArr shouldn't have side effects, anyway. Just take it out.


Style and Warnings

I'm not sure if you just omitted it from your code, but your code depends on functions declared in external header files in the standard library. Include these at the top of your file.

#include <stdlib.h>
#include <stdio.h>

Next, let's talk about code style. You are writing some very densely-packed expressions in some places. Some whitespace can make code much more readable! For example, change the for loops to this:

for (int i = 0; i < n; i++)

Similarly, change your allocation to this:

int * arr = malloc(sizeof(*arr) * n);

Proper spacing makes code more readable and therefore more maintainable!

Finally, let's talk about pointer declarations. You are declaring your pointers with the asterisks just sort of "floating". This is actually not a bad compromise. Some people prefer them to be grouped with the type (int* foo), others with the name (int *foo). I prefer the former style, so in my final copy of the code, I changed them accordingly, but this is often merely personal preference.


Result

Here is all the code as it stands with the above changes implemented! Not only is it more readable due to style, but it's easier to understand the control flow since it no longer unnecessarily indirects variables via reference.

#include <stdlib.h>
#include <stdio.h>

int* initArr(int n)
{
    int* arr = malloc(sizeof(*arr) * n);
    for (int i = 0; i < n; i++) {
        arr[i] = i + 10;
    }
    return arr;
}

void printArr(int* arr, int n)
{
    for (int i = 0; i < n; i++)
    {
        printf("Arr element %d is %d\n", i, arr[i]);
    }
}


int main(void) {
    int* arr2 = initArr(10);
    printArr(arr2, 10);

    return 0;
}

Extra Notes

Can I use arr[i] anywhere in the functions instead of **arr? (Gave error when I tried it)

You can! But * has lower precedence than array subscript ([]), so you'd need to use grouping operators

(*arr)[i]

This became unnecessary with the other changes, though.

What is the most common way of dealing with arrays when writing professional code? Is my approach correct?

Depends on the situation. Honestly, the best away to handle arrays is to not use themโ€”if you're using a language with any more power than C, you should have higher-level language constructs (std::vector, ArrayList, etc.). However, if you have to use C, abstracting them behind an API is a good start.

One issue I'm encountering is having no way to tell printArr() what the size of the array is.

Yes, in C, arrays are just blocks of memory, so you can't get their length at runtime because it's not stored anywhere! If you wanted to do this, though, you could encapsulate your array in a struct.

typedef struct my_array {
    unsigned int length;
    int* data;
} my_array_t;

You could then return a my_array_t from initArr and pass a my_array_t to printArr, which could use arr.length to get the length.

2 of 3
6
  • Return values

    • initArr communicates the start address via both the return value and a pass-by-reference parameter. It surely is redundant. Normally you'd pick one of two possible signatures:

      int * initArr(int size);
      void initArr(int ** arr, int size);
      

    and stick to it.

    • printArr, as the name suggests, only produces a side effect of values being printed. It has nothing to report back except possibly errors encountered while printing. Make it void printArr(int *, int).
  • (Ab)use of sizeof

    initArr allocates an array of n units of a pointer size. This works by coincidence: in pretty much any platform space taken by a pointer is enough to accomodate an integer. However it is not guaranteed.

    printf("size is %d\n", sizeof(*arr)) is totally misleading. It is equivalent to printf("size is %d\n", sizeof(int *)), and doesn't depend on how many bytes are actually allocated. Try to pass size 0 to initArr.

Top answer
1 of 2
1

a=(int*)realloc(t,sizeof(int)); You are trying to reallocate dynamic memory to just one integer size every time in the loop. Instead take a local variable count for number of elements to read in as,

int count = 0; 
do
{
   printf("enter the element");
   scanf("%d",&n);
   printf("%d",a[i]);
   a = (int*)realloc(t, count * sizeof(int));
   a[count - 1] = n;
   i++;
} while(i<4);
free(a);
2 of 2
0

Lots of issues:

t=(int*)malloc(sizeof(int));

Don't cast the result of malloc (in C); it's unnecessary, and in older compilers it can suppress a useful diagnostic. Similarly, use the size of the actual object, rather than the type; that will save you some maintenance headaches:

t = malloc( sizeof *t );

Cleaner, easier to read, and not prone to issues if you decide to change the type of t. Although, given your code below, I think you meant for t to be a.

do
{
    printf("enter the element");

Standard output is line buffered, meaning output is held until either the buffer is full or you send a newline character. To make sure your output shows up immediately, use fflush:

    fflush( stdout );
    scanf("%d",&n);
    *a=n;

Has a been properly initialized to point anywhere yet? t and a are different objects, so assigning to t doesn't mean a is pointing anywhere meaningfule. Secondly, *a is equivalent to a[0]; are you sure you don't want to write

    a[i] = n;

especially given the line:

    printf("%d",a[i]);
    a=(int*)realloc(t,sizeof(int));

Same as above; drop the cast, use the size of the object itself:

    a = realloc( t, sizeof *a );

BUT, this has problems too. You're not actually extending your array; you keep allocating the exact same amount of space as when you started. And you keep using the same starting pointer, which may be different from your most recent result.

    i++;
}   while(i<4);

Here's what I think you're tryihng to do:

a = malloc( sizeof *a );
i = 0;

do
{
  printf( "enter a the element: " );
  fflush( stdout );
  scanf( "%d", &a[i] );
  printf( "%d\n", &a[i] );
  int *tmp = realloc( a, sizeof *a * (i+2) );   // +2 since i starts from 0
  if ( tmp )                                    // the array by one element
    a = tmp;                                    // only assign if realloc succeeded
} while ( ++i < 4 );

As a rule, extending an array one element at a time is expensive and inefficient; normally, you'd extend the array by some number of elements at once, reducing the number of times you have to call realloc:

size_t count = START_SIZE;
T *a = malloc( sizeof *a * count );
...
if ( idx == count )
{
  T *tmp = realloc( a, sizeof *a * (2 * count) );  // double the size of the buffer
  if ( tmp )                                       // each time we run up against
  {                                                // the limit.
    a = tmp;
    count *= 2;
  }
}
a[idx] = new_value;
Find elsewhere
๐ŸŒ
PrepBytes
prepbytes.com โ€บ home โ€บ c programming โ€บ dynamic array in c
Dynamic Array in C
June 19, 2023 - Explanation of the above code In the above example we have created two arrays of size 5 and 10 respectively and then we have assigned the values to the elements of the value after that we have printed both the arrays to show that the assigned values are assigned properly to the elements. Variable Size: Dynamic arrays allow for the allocation of memory at runtime, enabling the size of the array to be determined based on program logic or user input.
๐ŸŒ
Emory
mathcs.emory.edu โ€บ ~cheung โ€บ Courses โ€บ 255 โ€บ Syllabus โ€บ 2-C-adv-data โ€บ dyn-array.html
Emory
Do-it-yourself dynamic array in C ยท The C programming language does not have dynamic array as a language feature
Top answer
1 of 2
2

You increment num_places at the wrong time.

Change

  num_places++;
  weap_List[num_places] = new_weap;

to

  weap_List[num_places++] = new_weap;
2 of 2
1

Some quick thoughts:

for (i = 1; i < num_places; i++)
{

num_places, being an array index, will start at 0. This loop will fail badly with only zero or one weapons in your list. (The condition i < num_places is checked after the first iteration of the loop body. If weap_List has one element (at index 0), this loop will access memory that is not allocated and not print the weapon. Start array-handling loops at 0. The only times you should ever tolerate one-indexed arrays is when moving a huge amount of FORTRAN code to C; when starting from scratch, use zero-indexed arrays, as K&R intended. :)

   void *_tmp = realloc(weap_List, (num_allocated * sizeof(weapon)));
   weap_List = (weapon*)_tmp;

If _tmp were declared (weapon *) tmp = realloc(...), then you wouldn't need the (weapon *) cast on the next line.

Tiny nitpick: doubling the size is pretty expensive way to go when adding the 196609th weapon. Consider just growing by eight each time. (I'm guessing from your names that you're probably not going to be adding one item per second for weeks on end.)

Tiny nitpick: Avoid _prefix variable names, they are reserved for the C runtime environment. Yes, just about every program uses them, and yes, I've used them, and yes this one is probably safe :) but they are technically reserved. A plain tmp would suffice.

Larger nitpick: you're not checking the return value from realloc(3). It can fail. Your application should handle failure as gracefully as possible.

๐ŸŒ
Cprogramming
cboard.cprogramming.com โ€บ c-programming โ€บ 180909-dynamic-array.html
dynamic array
February 24, 2022 - Here are some modification in code to print entire array ยท Code: #include <stdio.h> #include <stdlib.h> int main() { int i; // Dynamically allocate memory using malloc() int* ptr = (int*)malloc(2 * sizeof(int)); // Check if the memory has been successfully // allocated by malloc or not if (ptr != NULL) { // Memory has been successfully allocated printf("Memory successfully allocated using malloc.\n"); // Get the elements of the array for (i = 0; i < 2; i++) { printf("The elements of the array are: "); scanf ("%d", ptr + i); } // Print the elements of the array printf("The elements of the arra
๐ŸŒ
Cplusplus
cplusplus.com โ€บ forum โ€บ beginner โ€บ 190963
Help Outputting Dynamic Array - C++ Forum
May 13, 2016 - 4. How does your function printArray() know the size of your passed array? 5. The way you are passing your array into your function crashes after outputting the first array value. Unless this is a class assignment you really should use the STL containers, std::vector is good when needed a dynamic ...
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ cprogramming โ€บ c_dynamic_arrays.htm
Dynamic Arrays in C
In this program, memory is first allocated dynamically for 5 integers using calloc(), where the values 1 to 5 are stored and displayed. After that, the memory block is expanded to hold 10 integers using realloc(), and new values are assigned to the additional elements. Finally, the complete array with both the old and new values is printed...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c language โ€บ dynamic-array-in-c
Dynamic Array in C - GeeksforGeeks
July 23, 2025 - We can use this function to create a dynamic array of any type by simply allocating a memory block of some size and then typecasting the returned void pointer to the pointer of the required type.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c language โ€บ dynamically-allocate-2d-array-c
How to dynamically allocate a 2D array in C? - GeeksforGeeks
January 10, 2025 - #include <stdio.h> #include <stdlib.h> int main(void) { int r = 3, c = 4; int* ptr = malloc((r * c) * sizeof(int)); /* Putting 1 to 12 in the 1D array in a sequence */ for (int i = 0; i < r * c; i++) ptr[i] = i + 1; /* Accessing the array values as if it was a 2D array */ for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) printf("%d ", ptr[i * c + j]); printf("\n"); } free(ptr); return 0; } ... 2) Using an array of pointers We can create an array of pointers of size r. Note that from C99, C language allows variable sized arrays. After creating an array of pointers, we can dynamically allocate memory for every row.
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ dynamic array in c
Dynamic Array in C - Scaler Topics
August 24, 2023 - They also generate much more Assembly ... be: ... Unlike other high-level languages (Python, JavaScript, etc), C doesn't have built-in dynamic arrays....