I have the following C code:
int main(int argc, char *argv[])
{
int n = argc - 1;
int array[n];
int m[n][n];
int i = 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]);
return 0;
}
If i run with the following command: “./program 30 35 15 5 10 20 15” the 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 the same pointer as m[n][n]. And i really don’t understand how this is possible. What is wrong with the code. Why does array[4] = m[n][n]?
Your loops are wrong, arrays in
Care zero-based. Meaning the first element isa[0]and the last isa[N-1]whereNis the size of the array.This:
Should be this:
Otherwise you overstep the array boundries.
As a side note, you are using VLA but didn’t specify a
C99tag. Be sure you know what you are doing.