Assigning values to a dynamically allocated array

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}}; */
 
J

Jack Klein

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}}; */


Arrays are modifiable lvalues in C. You can't assign to them. You
can only assign to the individual members, one-by-one. Perhaps you
could do that in a loop.

I would suggest that you read Section 6, "Arrays and Pointers", in the
FAQ for this group, link in my signature. Then I'd suggest you look
over the rest of the FAQ.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.club.cc.cmu.edu/~ajo/docs/FAQ-acllc.html
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top