0

In my code's output I find that the strings I am printing are all (null) even though I input count strings of characters < 31.

char name[31];
char *names[32];
int count = 5;
for (int i =0; i<count;i++) {
        scanf("%s",name);
        names[i]=(char*)malloc(strlen(name)+1);
        strcpy(names[i],name);
    }

for (int i =0; i<count;i++) {
    printf("%d: %s\n",i+1,names[count]);
}
1
  • Probably a typo, but printf("%d: %s\n",i+1,names[count]); should be printf("%d: %s\n",i+1,names[i]); - otherwise, you're printing an unallocated string. Commented Oct 22, 2020 at 22:13

3 Answers 3

2

Maybe you should use names[i] in stead of names[count]

for (int i = 0; i < count; i++) {
    printf("%d: %s\n", i+1, names[i]);
}
Sign up to request clarification or add additional context in comments.

Comments

2

you're indexing names with count but your code initialize string only up to count - 1. Changing printf this way:

printf("%d: %s\n",i+1,names[i]);

should do the trick.

Comments

1

Your error is in the printf function, you need to modify it in this way:

printf("%d: %s\n",i+1,names[count]); => printf("%d: %s\n",i+1,names[i]);

Comments

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.