R
Ray D.
I want to set matrix A with the values below, but it produced a syntax
error when I try to compile the commented code. I was told to use a
for loop to do this (as shown below), but that really isn't possible
considering I need these specific values. Is there a way to do this
in one statement instead of multiple statements of A[j] = ...,
where I manually specify the position? Why can you initialize like
this with a static array, but can't use the same syntax with a dynamic
array after the memory is allocated?
#define MATSIZE 8
....
int **A;
....
A = malloc(MATSIZE*sizeof(int *));
for (i = 0; i < MATSIZE; i++)
A = malloc(MATSIZE*sizeof(int));
for ( i=0; i < MATSIZE; i++ )
{
for ( j=0; j < MATSIZE; j++ )
A[j] = ...;
}
/* A = {{0, 1, 0, 0, 0, 3, 0, 0},
{0, 0, 0, 4, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 1},
{0, 0, 0, 1, 0, 7, 0, 0},
{6, 0, 8, 0, 0, 0, 2, 0},
{0, 0, 0, 0, 0, 3, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 5},
{0, 2, 0, 0, 0, 0, 1, 0}}; */
error when I try to compile the commented code. I was told to use a
for loop to do this (as shown below), but that really isn't possible
considering I need these specific values. Is there a way to do this
in one statement instead of multiple statements of A[j] = ...,
where I manually specify the position? Why can you initialize like
this with a static array, but can't use the same syntax with a dynamic
array after the memory is allocated?
#define MATSIZE 8
....
int **A;
....
A = malloc(MATSIZE*sizeof(int *));
for (i = 0; i < MATSIZE; i++)
A = malloc(MATSIZE*sizeof(int));
for ( i=0; i < MATSIZE; i++ )
{
for ( j=0; j < MATSIZE; j++ )
A[j] = ...;
}
/* A = {{0, 1, 0, 0, 0, 3, 0, 0},
{0, 0, 0, 4, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 1},
{0, 0, 0, 1, 0, 7, 0, 0},
{6, 0, 8, 0, 0, 0, 2, 0},
{0, 0, 0, 0, 0, 3, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 5},
{0, 2, 0, 0, 0, 0, 1, 0}}; */