Reputation: 505
So i did this program and the purpose is to store a string from the stdin and store in a array of strings. After that, i want to print all the strings stored in the array but in reverse order.
Example:
Input:
abc def hij klm nop
Output:
nop
klm
hij
def
abc
Program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLEN 1001
int main(){
char buffer[MAXLEN];
char** strings;
int i = 0;
int j = MAXLEN;
strings = (char**)malloc(sizeof(char*)*MAXLEN);
while(scanf("%s",buffer) == 3)
{
strings[i]=(char*)malloc(sizeof(char)*(strlen(buffer)+1));
strcpy(strings[i],buffer);
i++;
}
printf("%s",strings[0]);
}
Well, i just put the 1st string only to check if it was printing any strings the problem is that if type that in the example it prints (null)
instead of the word and what im wondering is why is it pointing to NULL instead of pointing to the string i gave.
Really any help would be appreciated.
Upvotes: 0
Views: 453
Reputation: 144770
The test for successful conversion from stdin
is incorrect: scanf()
returns the number of conversions, not the number of characters. You should compare the return value to 1
. As coded, the loop test fails immediately so strings[0]
is not modified, the code has undefined behavior because the array allocated by malloc
is uninitialized. This array happens to contain a null pointer at the beginning (because its first bytes are zero by coincidence), and printf
prints (null)
for null pointers, which is not guaranteed by the C Standard, but a useful indication sometimes.
Furthermore, you should tell scanf()
about the maximum length of a word to store into the destination array: scanf("%1000s", buf)
.
You should also limit the number of words you tore into the array of pointer and test for memory allocation error.
Finally, you need a loop to output the strings in reverse order of input.
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLEN 1001
int main() {
char buffer[MAXLEN];
int i, j;
char **strings = malloc(sizeof(char *) * MAXLEN);
if (strings == NULL)
return 1;
for (i = 0; i < MAXLEN && scanf("%1000s", buffer) == 1; i++) {
strings[i] = strdup(buffer);
if (strings[i] == NULL)
return 1;
}
for (j = i; j-- > 0;) {
printf("%s\n", strings[j]);
free(strings[j]);
}
free(strings);
return 0;
}
Upvotes: 1