I think your code should be this:
#include <stdio.h>
#include <conio.h>
int main() {
char v[20];
for(int i = 0; i < 20; i++) {
char c;
scanf("%c", &c);
v[i] = c;
}
for(int i = 0; i < 20; i++) {
printf("%c ", v[i]);
}
getch();
}
I tested it here and it worked. I just had to remove #include <conio.h>
and put return 0;
instead of getch();
.
Remember that in C every vector is a pointer, so char v[20];
is a pointer to a character. It only happens that this pointer points to an area of memory already allocated in the stack for 20 characters.
char *v[20];
is a pointer to another character pointer, which points to a memory area on the stack where 20 other pointers fit. This is not what you want!
The v[i] = &c;
code is particularly dangerous. You get the memory address of the c
variable and place it in the character vector. This operation has no meaning at all, in addition the size of the memory address does not fit in the position of the vector, so the resulting value will be truncated. The result will be that you are polluting your vector with garbage.
*v[i] = c;
means that you get the i-th character of v
, interpret it as a pointer and dereference, and set the c
value to the resulting memory location. This is not what you want, you do not want to interpret the i-th character as a pointer. This is most likely to cause a segmentation flaw in the program or something else disastrous.
Now, looking at the code I've corrected, notice that you hardly need to dereference explicit pointers, just work with arrays. The only detail is scanf
, where you get the c
address only.
Another detail of your code: It will always try to read the 20 characters, even if what you want to type is smaller than that. To resolve this, in case you want to, you will have to verify that the user typed \n
and stop.