Reputation: 1559
Hi I m debugging a C app and seing this strange behavior in an array of 10 rows and 4 columns:
void fillArray(int *B){
//DEBUG
printArray(B,10,4);//printing all items 0's
B[3,0] = 3;
printArray(B,10,4); // results in B[0,0] = 3 , B[1,0] = 3 , B[2,0] = 3 , B[3,0]= 3 , ...
// Rest values remains zero.
}
void printArray(int *B,int imax,int jmax){
printf(" \n --- Check---");
for(i=0;i<imax;i++){
for(j=0;j<jmax;j++){
printf(" \n Check: B[%d,%d]=%d ",i,j,B[i,j]);
}
}
}
Why does value 3 is inserted in every row of the table for column 0 ?
Upvotes: 0
Views: 46
Reputation: 53016
Because the ,
operator discards all the operands except the last. So this
B[3,0] = 3;
is effectively
B[0] = 3;
and how many columns does your table have? since it's an int *
I doubt that you have a table. The suggested syntax
B[3][0] = 3;
is wrong too, because B[3]
has type int
and you cannot index an int
.
Upvotes: 0
Reputation: 23717
In C, the syntax for two-dimensional arrays is:
B[3][0] = 3
rather than:
B[3,0] = 3;`
,
is the comma operator which has an other meaning (basically, the value of the expression a, b
is b
).
Upvotes: 1
Reputation: 21288
You're using the expression 3, 0
to index the array. That expression has the value 0 (it's using the sequence operator, the value of which is the value of the last expression, in this cas e a constant 0). To index a multi-dimensional array in C, you need to use something like m[a][b]
.
Upvotes: 1