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.
scanfmanual page, it returns the number of items successfully matched and assigned. Your"%s"is looking for one item, so it's not going to return a 3. Where did you get 3 from? Tryscanf("%s",buffer) == 1.strings = (char**)malloc(sizeof(char*)*MAXLEN);-->MAXLENhas nothing to do with the size needed. It depends on the iteration count of the following loop.