Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
410 views
in Technique[技术] by (71.8m points)

c - What does char **text = (char **) malloc(n * sizeof(char*)); does?

i just started with programming and i don't know what does this mean ..

I tried everything i could..

I know its dynamic memory allocation but don't know what all these (stars) means. Could someone explain me, what every type is? This is the code:

char **text = (char **) malloc(n * sizeof(char*));
text[i] = (char *) malloc(MAX_LENG);
question from:https://stackoverflow.com/questions/65907858/what-does-char-text-char-mallocn-sizeofchar-does

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The code allocates (dynamic) memory for holding n strings. Each of these strings with max length MAX_LENG - 1.

I assume the complete original code to be:

char **text = (char **) malloc(n * sizeof(char*));
for (int i = 0; i < n; ++i)
    text[i] = (char *) malloc(MAX_LENG);

or without the unnecessary casts:

char **text = malloc(n * sizeof(char*));
for (int i = 0; i < n; ++i)
    text[i] = malloc(MAX_LENG);

So the first line, i.e.

char **text = malloc(n * sizeof(char*));

will give you a pointer to a memory area holding n pointers-to-char

The loop, i.e.

for (int i = 0; i < n; ++i)
    text[i] = malloc(MAX_LENG);

then makes each of these n pointers point to a memory area with MAX_LENG chars.

It looks like:

enter image description here

So after this you have memory for n strings and can use them like:

strcpy(text[0], "HELLO");  // First string is "Hello"
strcpy(text[1], "WORLD");  // Second string is "World"

After this it looks like:

enter image description here

You can access the individual charaters like this

char c = text[1][4]; // c now holds the character 'D' from the string "WORLD"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...