I want to input strings to an array in C, the code I have is this:
int main()
{
int sizeA;
printf("Tamanio de arreglo\n");
scanf("%i", &sizeA);
char names[sizeA];
for(int i = 0; i < sizeA; i++){
printf("Nombre %c\n", i+1 );
scanf("%c", &names[i]);
}
printf("valores arreglo\n");
for(int i = 0; i < sizeA; i++){
printf("%c", names[i]);
}
return 0;
}
First of all I ask the size of the array, in case of entering 5
as the length of the array, when I enter the value of the strings at the time of requesting the Nombre
name, I get the name request twice, which in the end allows me to enter 2
the string only times and not the 5
ones you enter as length. How can I enter the 5 values? Thanks in advance. When I do it with integers it lets me enter the 5 values correctly and with strings it doesn't.
Several things to keep in mind:
In C, the size of arrays must be constant. The compiler should refuse to compile.
To solve the first problem, you must resort to dynamic memory if you need variable-length arrays.
You can allocate and free memory with
malloc
andfree
respectively. For example:It is preferable to use
scanf
only to read numbers or Boolean values. For characters or strings (no need to read or write characters individually),getchar
andgets_s
are better options.When reading numbers,
scanf
it drops the line break similar to how it does in C++.In C you can discard the character with
getchar
(equivalent tofgetc(stdin)
). In C++ you can do it withstd::cin.ignore()
.A string is an array of characters (
char*
orchar[]
). If you want an array of strings, it would bechar[][]
,char*[]
,char[]*
orchar**
(the more you work with dynamic memory, the more likely you are to use the latter).Some examples:
With all the fixes, you would get code like this:
You can try it here .