首页 > 解决方案 > 无法获取字符串数组中的第一个字符

问题描述

我想获取每个字符串的第一个字符。这里有一个例子:

#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 循环中,程序陷入分段错误。我不知道为什么。

标签: c

解决方案


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您相同的结果:mallocstrcpy

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

推荐阅读