c++ - Simple Pointer Array Equality Explanation Needed -
just going bit of c++ programming uni , remembered why thought pointer business crazy. give me quick explanation whats happening here? possible int 20 in main function?
#include <stdio.h> void test(int *b) { b[0] = 10; b[1] = 20; printf("\n %i \n ", b[1]); // prints 20 } int main( int argc, char* argv[] ) { int a; test(&a); printf("%i \n", a); //prints 10 // printf("%i \n", a[1]); // doesn't compile - why not 20? return 0; }
edit: sorry simple question such burden users deal , thank users did take , inform me undefined behavior. reason asked question code found couldn't work out how use. did not pull out of air. here if interested. @ glhunprojectf function , last argument how meant use it.
http://www.opengl.org/wiki/gluproject_and_gluunproject_code
honestly, i'm sort of surprised lets assign value b[1]. guess if took out part not compile, segfault when try assign 20 b[1], because program hasn't been allocated space in memory. anyway, int not pointer, it's variable, can't indexed array.
just recap, here's breakdown of variables , pointers have:
int - integer variable in memory, program cares value of integer, not in memory.
&a - returns pointer integer in memory. because pointers arrays pointers first element in array, program not complain when try index it
int* b - a, pointer integer, not integer itself. mentioned, pointers can indexed arrays ([0], [1] , on) because pointer array pointer first element in array. mentioned, trying index past memory space you've been allocated, whether or not have array index, undefined behavior (most of time give segmentation fault, might return value happens in memory @ location, literally anything, isn't guaranteed same data type).
Comments
Post a Comment