开发者

Taking strings as input into an array of pointers to strings and displaying them

I intend to store strings into an array of pointers to strings and then display them as foll开发者_如何学Goows :

char *directions[3]; for(i=0;i<3;i++) scanf("%s",directions[i]); for(i=0;i<3;i++) printf("%s",directions[i]);

but when i run this code ,it gives me segmetation fault ,could someone please correct me?


You have an array of size 3 of pointers to characters. These pointers do not point to any valid memory where you could possibly store some of those strings that you are reading in. Trying to write to invalid memory invokes UB. Here, UB manifests in the form of a segmentation fault (most probably because you are trying to write to a location you have no control on).

Try allocating some memory first: Say a big enough buffer to read in an entire line (or the biggest string that you think you are going to encounter). Read in, allocate a direction array member and then copy it out as follows:

char *directions[ 3 ];
const MAX_LINE_SIZE = 256;
char line[ MAX_LINE_SIZE ];

for (size_t nstr = 0; nstr < 3; ++nstr) {
      if (fgets( line, MAX_LINE_SIZE, stdin ) != NULL) {
           directions[ nstr ] = malloc( strlen( line ) );
           strcpy( directions[ nstr ], line );
      }
      printf( "%s\n", directions[ nstr ] );
}


All you have is pointers to string. You need to make these pointers point to valid memory locations before you try to read using scanf.

// allocate memory.
for(i=0;i<3;i++)
    directions[i] = (char*)malloc(sizeof(char) * SUITABLE_MAX);

// now read.
for(i=0;i<3;i++)
    scanf("%s",directions[i]);


char *directions[ 3 ];
const MAX_LINE_SIZE = 256;
char line[ MAX_LINE_SIZE ];

for (size_t nstr = 0; nstr < 3 && fgets( line, MAX_LINE_SIZE, stdin ); ++nstr) {
  strcpy(directions[ nstr ] = malloc( strlen( line )+1 ),line);
  puts(directions[ nstr ]);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜