0

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 malloced 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]);
}
4
  • 3
    Your strings are not null-terminated. Commented May 5, 2013 at 23:19
  • 1
    Also, malloc(20000) allocates 20000 bytes, and you're then trying to fill it with 20000 character pointers (which take several bytes each, and are overwriting each other). Commented May 5, 2013 at 23:27
  • Yeah, I should have done this text = malloc(20000 * sizeof(char *)); Commented May 5, 2013 at 23:29
  • And nick is also right...you need to allocate 5 bytes for the string "text" to accommodate the null terminator. Commented May 5, 2013 at 23:30

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

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

}

1 Comment

Or, of course, change the first malloc(20000) to malloc(20000 * sizeof(char *)).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.