Without using the following code how can I initialize an entire column of a 2D-array with a particular value, say 1?
int a[row][col];
for(i=0; i<row; i++)
{
a[i][col]=1;
}
Without using the following code how can I initialize an entire column of a 2D-array with a particular value, say 1?
int a[row][col];
for(i=0; i<row; i++)
{
a[i][col]=1;
}
As of C99, standardized 15 years ago, you can use explicit indexing:
int a[10][10] = { [0][0] = 1, [1][0] = 1, /* more code here */, [9][0] = 1 };
With GCC you can use even more powerful syntax but of course you lose portability and are no longer programming in standard C.
C99 and latter will let you initialize the entire row/column using designators. But you can't assign 1
to entire column without using a loop.
int a[n]= {1};
will initialize first element of array to 1
and rest of elements will be initialized to 0
by default. It is not initializing all elements to 1
. These are the areas of C where you need loop.
if you want to initialize all the elements of the 2D-array by the same number you can proceed by what gcc provides for a good array initialization shortcut for instance :
int a[5][6]={ [0 ... 4][0 ... 5]=1};
to see the effect we can use the loop
int i,j;
for(i=0; i<5; i++)
{
for(j=0; j<6; j++)
printf("%d ",a[i][j]);
printf("\n");
}
which generate the matrix
1 1 1 1 1 1
1 1 1 1 1 1
1 1 1 1 1 1
1 1 1 1 1 1
1 1 1 1 1 1
There is another possibility by using memset()
but it is only restricted for type char (-128 ... 127 ) or unsigned char (range between 0 ... 255)
If you are SURE that the values of the array will not at any case exceed the limits then you can use it by defining the array like that
char a[row][column];
and initialize it with the memset function in string.h
library
memset ( a,1, sizeof(a));
What you have is fine for a column.
If you want to init the entire array use :
for (i=0; i < sizeof(a)/sizeof(int) ; i++) {
a[i] = 1;
}
The above initializes array a
using a single loop counter. Since a
is an array of type int
and not char
, you cannot use memset()