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 the #include <conio.h>
and put a return 0;
in place of getch();
.
Remember that in C every vector is a pointer, so char v[20];
is a pointer to a character. It just so happens that this pointer points to an area of memory already allocated on the execution stack (stack) for 20 characters.
Already char *v[20];
is a pointer to another character pointer, which points to an area of memory in the stack where 20 other pointers fit. That’s not what you want!
The code v[i] = &c;
is particularly dangerous. You take the memory address of the variable c
and puts it in the character vector. This operation has no sense, besides the memory address size does not fit in the vector position, so the resulting value will be truncated. The result will be that you are polluting your vector with garbage.
Already *v[i] = c;
means you take the i-th character of v
, interprets it as a pointer and the override, and puts the value of c
in the resulting memory position. That’s not what you want, you don’t want to interpret the i-th character as if it were a pointer. Most likely this causes a segmentation failure in the program or something else disastrous.
Now, looking at the code I fixed, note that you almost don’t need to de-reference explicit pointers, just work with arrays. The only detail is the scanf
, where you get the address of c
only.
Another detail of your code: It will always try to read the 20 characters, even if what you want to type is less than that. To resolve this detail, if you want, you will have to check if the user has typed \n
and stop.
So, the statement of the exercise is as follows: "Create a pointer variable of type vector with 20 character occurrences. Load this vector by reading these occurrences and store it in memory." So I thought I’d need to do the vector as a pointer in itself... But one thing is still happening even with your code, it only reads half of the characters it should, if I put 20 in the go, it reads 10, if I put 10, it reads 5, has any idea why?
– Tryedz
@Tryedz "Create a pointer variable of type vector", this is exactly what the
char v[20];
is. It is a pointer variable and its type is a vector. If the idea is to use achar*
So the statement is misspelled, but that’s easy to fix. As for this business of only reading half, are you typing ENTER after each character? It considers ENTER one character as any other.– Victor Stafusa