dynamic 2 D array with malloc??

B

Barry Schwarz

Thank you very much. I have fixed the problem/ Now I am confused how
to free this 2D array:


If my code is as follows:

int **xyz;
int i, r = 3, c = 30000;


xyz = malloc(r * sizeof(*int));

Since *int is a syntax error, I will assume you meant *xyz.
for (i = 0; i < r; ++i)
xyz = malloc(c * sizeof **xyz);

how to free this memory block:

for (i=0;i<r;i++)
free xyz;


free is a function, not a statement. I will assume you meant
free(xyz);

There should be a free for each malloc. You have r+1 calls to malloc
but only r calls to free. You are missing
free(xyz);
does it work?

and one more question what is difference between :

for (i = 0; i < r; ++i)

and

for (i = 0; i < r; i++)

In this case, you are not using the value of either ++ operator. You
are only using the side effect (the fact that i is incremented). Since
the side effect is the same, there is no difference.


Remove del for email
 
J

Joe Wright

Richard said:
Joe Wright said:

int **xyz;
int i, r = 3, c = 30000;

xyz = malloc(r * sizeof *xyz);
for (i = 0; i < r; ++i)
xyz = malloc(c * sizeof **xyz);

What do you think?


I think xyz could be NULL at the point where you deref it. Why, what do
/you/ think? :)

I have fixed my machine so that malloc() never fails. :=)
 
P

Peter Shaggy Haywood

Groovy hepcat Nick Keighley was jivin' on 15 Mar 2007 08:28:01 -0700
in comp.lang.c.
Re: dynamic 2 D array with malloc??'s a cool scene! Dig it!
i am trying to create a dynamic 2D array with size N x 3 (N will be
put in as a parameter) using the following code:

int **xyz;
int i,N;

by convention uppercase is reserved for macros.

N=30000;
xyz=malloc(3*sizeof(int*));

since 3 is fixed you could do

int *xyz[3];

Or rather, since it's supposed to be N x 3, not 3 x N

int (*xyz)[3];
....
xyz = malloc(N * sizeof *xyz);
....

Then the whole thing is allocated in one shot, used as a 2D array
(except when the operand of & or sizeof) and, when finished, freed in
one shot.

--

Dig the even newer still, yet more improved, sig!

http://alphalink.com.au/~phaywood/
"Ain't I'm a dog?" - Ronny Self, Ain't I'm a Dog, written by G. Sherry & W. Walker.
I know it's not "technically correct" English; but since when was rock & roll "technically correct"?
 
K

Kevin D. Quitt

Could be worse - could be allocating 3D arrays. I just happen to have an
example of that...
 

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,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top