【问题标题】:Segmentation fault: Pointer to an array of string [duplicate]分段错误:指向字符串数组的指针[重复]
【发布时间】:2015-07-24 11:41:50
【问题描述】:

我有一个初始化为 NULL 的字符串数组 (char **)。当我尝试访问它的元素时传递它的地址后,它会出现分段错误。

//following code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


void parse(char ***test, char *str)
{
    int i;
    *test = (char**)malloc(sizeof(char*) * 3);
    for(i=0; i<3; i++)
    {
        *test[i] = (char*) malloc(sizeof(char)*(strlen(str)+1));
        strcpy(*test[i], str);
    }
}

int main(void)
{
    int i;
    char *str = "Hello world";
    char **test = NULL;
    parse(&test, str);
    for(i=0; i<3; i++)
        printf("%s\n", test[i]);
    return 0;
}

在函数解析中使用调试器时,所有元素都具有正确的值并正确初始化和分配,但从主函数中只有 0 索引行给出正确的值其余是段错误。

【问题讨论】:

  • malloc()和好友的结果不需要投,也不建议以任何方式投。

标签: c arrays string pointers segmentation-fault


【解决方案1】:

*test[0] 应该是(*test)[i]

http://en.cppreference.com/w/c/language/operator_precedence 表示[] 的优先级高于*,这不是您想要的。

您也不应该覆盖索引 0。

sizeof(char) 始终为 1,因此您可以不使用它。您也不应该强制转换 malloc 的返回值并测试是否成功。

【讨论】:

  • 这从来没有打动过我!!惊人的。非常感谢!
【解决方案2】:

这里的问题是

*test[0] = (char*) malloc(sizeof(char)*(strlen(str)+1));

你总是将内存分配给索引0

此外,在operator precedence table 之后,您需要先取消引用test,然后对其应用索引,因此,您基本上需要重新编写代码,例如

(*test)[0]  = malloc( strlen(str) + 1);

请注意:

  1. See why not to castmalloc()C中的family的返回值。

  2. sizeof(char) 保证产生1。乘以它是多余的。

【讨论】:

  • 那是一个错字!!我已经编辑了!!问题依然存在!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-24
  • 2014-11-29
相关资源
最近更新 更多