By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,654 Members | 936 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,654 IT Pros & Developers. It's quick & easy.

Malloc for array of string

P: n/a
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[i] = mxMalloc(n *sizeof(char));}
//how do i free this?

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

thanks in advance..

Jun 20 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a
dk*******@gmail.com wrote:
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[i] = mxMalloc(n *sizeof(char));}
//how do i free this? The code below frees it.
for (i=0;i<m;i++){
mxFree(s_array[i]);
}
mxFree(s_array);
please point out the errors..


Jun 20 '06 #2

P: n/a
On 20 Jun 2006 03:01:07 -0700, dk*******@gmail.com wrote:
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[i] = mxMalloc(n *sizeof(char));}
sizeof(char) is guaranteed to be 1 so using it here gains you nothing.
Using the preferred idiom
s_arry1[i] = malloc(n * sizeof *s_array[i]);
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[i]);
}
mxFree(s_array);
please point out the errors..


There are no standard functions name mxMalloc and mxFree.
Remove del for email
Jun 21 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.