c - 无法获取字符串数组中的第一个字符
问题描述
我想获取每个字符串的第一个字符。这里有一个例子:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main() {
int size = 2;
char** text = (char**) malloc(sizeof(char*) * size);
for(int i = 0; i < size; ++i) {
char buf[80];
fgets(buf, 80, stdin);
text[i] = (char*)malloc(strlen(buf));
strcpy(text[i], buf);
}
for(int i = 0; i < strlen(text[i]); ++i) {
printf("%c ", text[i][0]);
}
}
在最后一个 for 循环中,程序陷入分段错误。我不知道为什么。
解决方案
该strlen
函数返回给定字符串中不包括终端nul
字符的字符数;但是,该strcpy
功能会复制所有字符,包括终止字符nul
!
因此,您的分配text[i]
不够大,并且通过超出缓冲区的范围写入,您将获得未定义的行为。
在调用中添加一个额外的字符malloc
:
for(int i = 0; i < size; ++i) {
char buf[80];
fgets(buf, 80, stdin);
text[i] = malloc(strlen(buf) + 1); // Need space for the terminal nul!
strcpy(text[i], buf);
}
或者,更简单地说,使用该功能,它可以一举达到与strdup
您相同的结果:malloc
strcpy
for(int i = 0; i < size; ++i) {
char buf[80];
fgets(buf, 80, stdin);
text[i] = strdup(buf);
}
无论哪种方式,不要忘记调用free
您分配的所有缓冲区。
编辑:您在最终输出循环中也使用了错误的“限制”;这:
for(int i = 0; i < strlen(text[i]); ++i) { // strlen() is not the # strings
printf("%c ", text[i][0]);
}
应该:
for(int i = 0; i < size; ++i) { // "size" is your number of strings!
printf("%c ", text[i][0]);
}
推荐阅读
- python - 如何在 PyCharm 中正确导入 libtcod?
- excel - 索引和匹配多个条件
- java - 多查询和参考 Firebase 数据库 Android
- laravel-5.5 - laravel 将 5.4 升级到 5.5 并出现 401 未经授权的 ajax 问题
- c++ - 分配非 const 变量的只读位置
- azure - Azure APIM 在将 Content-Type 作为应用程序/json 传递时验证 base64 编码的文本?
- python - 如何将字典键(元组)及其值组合成一个字符串?
- amazon-dynamodb - 如果不存在任何项目,DynamoDB Mapper batchLoad 会返回什么?
- javascript - 尝试使用传单映射坐标时获取无效的 LatLng 对象
- ios - 将数据从 ViewController 传递到 UITableViewController