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]);
}
  • 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. – Adrian Mole Oct 22 '20 at 22:13

3 Answers3

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]);
}
Chems Eddine
  • 153
  • 6
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.

LeonFibuck
  • 336
  • 2
  • 12
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]);

Zig Razor
  • 3,381
  • 2
  • 15
  • 35
0___________
  • 60,014
  • 4
  • 34
  • 74