I am trying to read some strings and then print them into a matrix form.
int main(int argc, char **argv)
{
char *buffer[BUFFER_SIZE];
for(size_t i = 0; i < BUFFER_SIZE; i++)
{
scanf("%s",buffer[i]); /**This line is causing segment fault **/
}
for(size_t i = 0; i < BUFFER_SIZE; i++)
{
for(size_t j = 0; j < strnlen(buffer[i], MAX); j++ )
{
printf("%c ",buffer[i][j]);
}
printf("\n");
}
}
Any suggestion what I am missing here?
char *buffer[BUFFER_SIZE]
is an array of character pointers. The way your code is now, buffer[i]
is a char *
that is uninitialized at the time you scanf("%s",buffer[i])
. You need to allocate memory ( malloc
, perhaps) for scanf
to store the string of characters prior to this point.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.