0
I want to make a list of strings but it always implements the last words.I dont know where's my mistake.Help me. Thank you:)))
#include<stdio.h> #include<string.h> int main(){ int n; scanf("%d",&n); char s[100]; char *x[n]; for(int i=0;i<n+1;i++){ fgets(s,100,stdin); x[i]=s; } for(int i=0;i<n+1;i++){ printf("%s",x[i]); } return 0; }
5 ответов
+ 4
You have two mistakes:
1st: when you create an array in the stack you should specify the number of elements you want before compilation.
If you want to enter the number of elements in runtime you should use dynamic memory allocation to allocate memory in the heap.
2nd: i should be just less than n, so it starts with index zero and iterates n times.
+ 3
Use malloc or calloc to allocate memory for x and after printing x use free function to deallocate the memory
+ 1
So you know how the variable 'x' is a pointer to a pointer? That would make the variable 's' a pointer.
I like to think about it as references. If 's' is just a pointer, or a "reference to a memory location", then it's not 's' that holds any data. It's the memory address that 's' points to. So every time you scan a new string into 's', the value that 's' points to changes as well, but not it's address. You also assign the same memory location to each space in 'x'. As you scan the final word, you actually change what's in each of 'x's pointers, because they are all the same address. That's why it only prints out the final word entered.
+ 1
pass a different mem address each iteration
0
So what should i change the code ???