Problems with pointers in C. The same pointer for different things -
i have next c code:
int main(int argc, char *argv[]) { int n = argc - 1; int array[n]; int m[n][n]; int = 0; for(i = 1; i<=n;i++) { array[i] = atoi(argv[i]); printf("%d\n",array[i]); } printf("array[4] = %d\n",array[4]); for(i = 1; i<=n;i++) { m[i][i] = 0; printf("address of m[i][i] = %p\n",&m[i][i]); } printf("value of array[4] =%d pointer = %p\n",array[4],&array[4]); for(i=1;i<=n;i++) printf("after %d\n",array[i]); homecoming 0; }
if run next command: "./program 30 35 15 5 10 20 15" output is:
30 35 15 5 10 20 25 array[4] = 5 address of m[i][i] = 0xbf93070c address of m[i][i] = 0xbf93072c address of m[i][i] = 0xbf93074c address of m[i][i] = 0xbf93076c address of m[i][i] = 0xbf93078c address of m[i][i] = 0xbf9307ac address of m[i][i] = 0xbf9307cc value of array[4] =0 pointer = 0xbf9307cc after 30 after 35 after 15 after 0 after 10 after 20 after 25
notice how array[4] has same pointer m[n][n]. , don't understand how possible. wrong code. why array[4] = m[n][n]?
your loops wrong, arrays in c
zero-based. meaning first element a[0]
, lastly a[n-1]
n
size of array.
this:
for(i = 1; <= n; i++)
should this:
for(i = 0; < n; i++)
otherwise overstep array boundries.
as side note, using vla didn't specify c99
tag. sure know doing.
c pointers
No comments:
Post a Comment