- #1
nobahar
- 497
- 2
Hello,
I was assigning a pointer to an array and I noticed it will only this to takeplace within the main function:
If I tried:
Why is this the case? Surely, once the array is declared it has an assigned place in memory; as such, the pointer can be assigned the arrays address. I am under the impression the code is "read" from top-to-bottom (kind of), and so the array is assigned a place in memory early on. I do not understand why I have to wait until main() to initialise the pointer.
Any help appreciated.
I was assigning a pointer to an array and I noticed it will only this to takeplace within the main function:
Code:
#include <stdio.h>
float array_1[10] = { 1,1,2,3,4,5,6,7,8,9 };
float * p_array_1;
int main( void )
{
p_array_1 = &array_1;
printf("array address using ampersand is %p and using element one is %p, and using pointer is %p", &array_1, &array_1[0], p_array_1);
printf("\nfloat size is %d", sizeof(float));
return 0;
}
Code:
#include <stdio.h>
float array_1[10] = { 1,1,2,3,4,5,6,7,8,9 };
float * p_array_1;
p_array_1 = &array_1;
int main( void )
{
printf("array address using ampersand is %p and using element one is %p, and using pointer is %p", &array_1, &array_1[0], p_array_1);
printf("\nfloat size is %d", sizeof(float));
return 0;
}
Why is this the case? Surely, once the array is declared it has an assigned place in memory; as such, the pointer can be assigned the arrays address. I am under the impression the code is "read" from top-to-bottom (kind of), and so the array is assigned a place in memory early on. I do not understand why I have to wait until main() to initialise the pointer.
Any help appreciated.