Malloc for array of string

D

dkumar142

Hello frnds,

I have a question. I know answer is quite easy but i think i am missing
some poiter or something..somewhere.

I have to define an array of string

char **s_array1;

now i have to allocate memory.. m strings and each string can hold n
characters..

//i guess.

s_array1 = mxMalloc(m*sizeof(char)); //should it be
sizeof(s_array1)!!
for (i=0;i<m;i++){
s_array1 = mxMalloc(n *sizeof(char));}


//how do i free this?

for (i=0;i<m;i++){
mxFree(s_array);
}
mxFree(s_array);
please point out the errors..

thanks in advance..
 
?

=?ISO-8859-1?Q?=22Nils_O=2E_Sel=E5sdal=22?=

Hello frnds,

I have a question. I know answer is quite easy but i think i am missing
some poiter or something..somewhere.

I have to define an array of string

char **s_array1;

now i have to allocate memory.. m strings and each string can hold n
characters..

//i guess.

s_array1 = mxMalloc(m*sizeof(char)); //should it be
sizeof(s_array1)!!

You want m char pointers. That's m*sizeof(char*), or m*sizeof *array1
for (i=0;i<m;i++){
s_array1 = mxMalloc(n *sizeof(char));}


//how do i free this?

The code below frees it.
for (i=0;i<m;i++){
mxFree(s_array);
}
mxFree(s_array);
please point out the errors..
 
B

Barry Schwarz

Hello frnds,

I have a question. I know answer is quite easy but i think i am missing
some poiter or something..somewhere.

I have to define an array of string

char **s_array1;

now i have to allocate memory.. m strings and each string can hold n
characters..

//i guess.

s_array1 = mxMalloc(m*sizeof(char)); //should it be
sizeof(s_array1)!!

You want m pointers to char, not m char.

You should use the recommended idiom
s_array1 = malloc(m * sizeof *s_array1);
which will work for any type of pointer.
for (i=0;i<m;i++){
s_array1 = mxMalloc(n *sizeof(char));}


sizeof(char) is guaranteed to be 1 so using it here gains you nothing.
Using the preferred idiom
s_arry1 = malloc(n * sizeof *s_array);
will make your code "self-adjusting" if you ever decide to change the
type of s_array1.
//how do i free this?

for (i=0;i<m;i++){
mxFree(s_array);
}
mxFree(s_array);
please point out the errors..


There are no standard functions name mxMalloc and mxFree.


Remove del for email
 

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

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top