#include <stdio.h>
#include <string.h>
#define max 50
#define len 30
char text[max][len];
void main(){
register int i;
printf("Enter an empty line to quit\n");
for(i =0 ;i<max;i++){
gets(text[i]);
if(!*text[i]){break;}
}
puts(text[1][0]);/*I want to display first character of second string but it doesn't print anything. Why??*/
}
如何从字符串数组中访问字符或字符串一部分
2条答案
按热度按时间mm9b1k5b1#
对于符合C标准的启动器,不带参数的函数
main
应声明如下函数
gets
不安全,C标准不支持。请改用标准C函数fgets
。函数
puts
需要一个指针类型为char *
的参数,该参数指向一个字符串。但是,您传递的对象类型为char
会引发未定义的行为。
同时在变量使用的最小作用域中声明变量,在文件作用域中声明数组
text
没有多大意义。该程序可以如下所示
注意,函数
fgets
可以将新的行字符'\n'
存储在提供的数组中。如果你想删除它,你可以写
nc1teljy2#
在您的代码中,
puts(text[1][0])
试图打印text[1][0]
,而text[1][0]
是char
,而puts
只接受char*
,这导致我的计算机上出现分段错误。但是,
printf
允许您打印char
。固定代码:
注意:正如问题注解中所述,您也可以使用
putchar()
打印一个字符。输入:
输出: