How do I enter a string into a 2d array in C?
There are 3 ways which are mentioned below.
If you know the maximum number of lines and the maximum number of characters, you can use the method below to declare a character array.
char strs[MAX_NO_OF_STRS][MAX_NO_CHARS] = {0};
for (i = 0; i < MAX_NO_OF_STRS; i++)
{
scanf("%s", strs[i]);
}
If you know the maximum number of lines and you don't want to waste memory allocating memory MAX_NO_CHARS
for all lines. then go to array of char pointers.
char temp[MAX_NO_CHARS] = {0};
char *strs[MAX_NO_OF_STRS] = NULL;
for (i = 0; i < MAX_NO_OF_STRS; i++)
{
scanf("%s", temp);
strs[i] = strdup(temp);
}
If you know the maximum number of lines at runtime, you can declare a double pointer char
. Get the number of rows n
from the user and then allocate the memory dynamically.
char temp[MAX_NO_CHARS] = {0};
char **strs = NULL;
int n = 0;
scanf("%d", &n);
strs = malloc(sizeof(char*) * n);
for (i = 0; i < n; i++)
{
scanf("%s", temp);
strs[i] = strdup(temp);
}
source to share
An alternative to using malloc
and filling an array of pointers with fixed-size buffers would be to allocate a 2d array (in static storage or on the stack) and fill it. An example of modified KingsIndian code would look something like this:
#include <stdio.h>
int main()
{
char str[2][256] = {{0}};
int i = 0;
for(i=0;i<2;i++)
{
scanf("%255s", &str[i][0]);
}
return 0;
}
If all the strings you expect to receive are no larger than a certain size, then this approach will save you the trouble of freeing memory yourself. However, it is less flexible, which means that you cannot fit the size of an individual buffer to the string it contains.
EDIT
Adding to the information in the comments, we read a line that only ends with a newline, not any space:
scanf("%255[^\n]", str[i]);
source to share