以字符串作为输入指针数组为字符串并显示它们 [英] Taking strings as input into an array of pointers to strings and displaying them

查看:99
本文介绍了以字符串作为输入指针数组为字符串并显示它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打算把字符串存储到指针数组为字符串,然后显示它们如下:

I intend to store strings into an array of pointers to strings and then display them as follows :


字符*方向[3];
对于(I = 0; I&下; 3;我+ +)
scanf函数(%S,方向[I]);
对于(I = 0; I&下; 3;我+ +)
的printf(%S,方向由[i]);

但是当我运行此code,它给了我segmetation故障,可能有人请纠正我?

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

推荐答案

您必须指向字符的大小为3的数组。这些指针不指向任何有效的记忆在这里你可能存储一些那些你正在阅读的字符串。试图写无效的内存调用UB。在这里,UB在分割故障的表现形式(最可能是因为你试图给你写信对无法控制的位置)。

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 ] );
}

这篇关于以字符串作为输入指针数组为字符串并显示它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆