简体   繁体   中英

Array of array of string in c with malloc

Can you tell me what am I doing wrong here ? I don't get the text when I print printf("%s\\n",text[0]);

I created char **text; and malloc ed all pointers.

#include<stdio.h>
#include<string.h>
#include<stdlib.h>


char **text;

int main()
{
    int i; 
    text = malloc(20000);


    for(i=0; i < 20000; i++) {
        text[i] = malloc(4);

        memcpy(text[i], "test",4);
    }
    printf("%s\n",text[0]);
    printf("%s\n",text[1]);
}

I believe you're looking for something like this:

int numElements = 20000, i;
// Allocate an array of char pointers
text = malloc(numElements * sizeof( char *)); 

for( i = 0; i < numElements; i++) {
    // 4 for the length of the string "test", plus one additional for \0 (NULL byte)
    text[i] = malloc( (4 + 1) * sizeof( char));
    memcpy( text[i], "test\0", 5);
}

Here is an online demo showing it working, as it produces the output:

test
test
for(i=0; i < 20000/sizeof(char*); i++) {
    text[i] = malloc(5);
    memcpy(text[i], "test",5);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM