I have a code in C with these lines included:
int i;
int *serie = malloc(sizeof(int));
for (i = 0; i <= 20; i++){
serie=rand();
printf("%d ",&serie[i]);/* *serie */
}
It does work but I want to know why, with malloc I believe I am creating a dynamic array or pointer called serie so far my knowledge is:
& returns the address
* returns the content of the adress
With fixed arrays you use [] and with pointers ()
By testing &serie[i] seems to work but It does not *serie(i) or *serie[i] and *serie I think It does not too.
Can someone explain me these?
If I wanted to print the contents should not I put * instead of &, I think with dynamic arrays you use [] instead of () so it should be *serie[i] not &serie[i]?
In this code,
serieis a pointer to an integer. The line withmalloc()allocates space for it, such that setting or getting an integer to/from*seriewill work. The loop seems to incorrectly be setting the return value ofrand()(an integer) toserie. That particular line should look like this, in your current code (but it’s not what you want anyway):Because
rand()returns an integer, andseriealone is a pointer to an integer. However,*serieis an integer that you can set to.In the
printf(), you’re trying to accessserieas an array, but that won’t work because you’ve only allocated a single element. Well, it will work, but only for element zero.If you’re trying to set and generate 20 random elements (but using a “dynamic” array), you might want something like this:
Note that any time you use square brackets to access an element, it’s dereferencing it, much like
*does. Soserie[i]and*(serie + i)are functionally equivalent.