Declaring arrays in c language without initial size
You will need to declare temp
as an int
pointer (instead of an int
array). Then, you can use malloc
in your main
(after your first scanf
):
temp = malloc(d * sizeof(int));
In C arrays and pointers are closely related. In fact, by design an array is just a syntax convention for accessing a pointer to an allocated memory. *(see note for more details below)
So in C the statement
anyarray[n]
is the same as
*(anyarray+n)
Using pointer arithmetic.
You don't really have to worry about the details to make it "work" as it is designed to be somewhat intuitive.
Just create a pointer, and allocate the memory and then access it like as an array.
Here is some examples --
int *temp = null; // this will be our array
// allocate space for 10 items
temp = malloc(sizeof(int)*10);
// reference the first element of temp
temp[0] = 70;
// free the memory when done
free(temp);
Remember -- if you access outside of the allocated area you will have unknown effects.
- To be clear it is the indexing operator (
[ ]
) that is translated to pointer arithmetic. This is not an array in the modern sense of the type. Whether (or not) the pointer involved points to (dynamically) allocated memory is inconsequential to how this operator works. In a more modern language you would be able to operate on the array as an abstract type (to see how big it is, for example), you can't do this in C.
An array without an initial size is basically just a pointer. In order to dynamically set the size of the array, you need to use the malloc()
or calloc()
functions. These will allocate a specified amount of bytes of memory.
In your code above, declare temp
as an int pointer
int *temp;
Then allocate space for it using malloc()
or calloc()
. The argument that these functions take is is the number of bytes of memory to allocate. In this case, you want enough space for d
ints. So...
temp = malloc(d * sizeof(int));
malloc
returns a pointer to the first byte in the block of memory that was just allocated. Regular arrays are simply pointers to the first byte in a sectioned off block of memory, which is exactly what temp
is now. Thus, you can treat the temp
pointer as an array! Like so:
temp[1] = 10;
int foo = temp[1];
printf("%d", foo);
Outputs
10