【问题标题】:Segmentation Fault with Character Pointer Array字符指针数组的分段错误
【发布时间】:2015-09-23 03:59:05
【问题描述】:

我是 C 的新手,尝试将指针数组的值复制到字符串时遇到了很多困难。我创建了一个包含这样一个指针数组的结构(双向链表实现的一部分)

typedef struct Node
{
    int value;
    char *args[41];
    ....
} Node;

当我想添加一个节点时,我一直在使用下面的方法

void addNew(char *args[], Node *current)
{
    // first node is passed in, so loop until end of list is reached
    while ((*current).next != NULL
        current = (*current).next;
    // create new node that is linked with the last node
    (*current).next = (Node *)malloc(sizeof(Node));
    ((*current).next)).prev = current;
    current = (*current).next;
    // assign value to new node
    (*current).value = some-new-value;
    // allocate space for new argument array
    (*current).args[41] = (char*)malloc(41 * sizeof(char*));
    int i=0;
    // loop through the arg array and copy each of the passed-in args into the node
    for (i=0; i<41; i++)
        strcpy((*current).args[i], args[i]);
    (*current).next = NULL;
}

我认为我的问题的根源在于我如何为新节点中的指针分配空间,但我无法弄清楚我做错了什么。就目前而言,一旦到达 strcpy 行,我就会收到分段错误(核心转储)。

知道我做错了什么吗?

【问题讨论】:

  • (*current).args[41](*current).args 中的第 42 个元素,这是一个仅包含 41 个元素的数组。

标签: c arrays pointers segmentation-fault


【解决方案1】:

线

(*current).args[41] = (char*)malloc(41 * sizeof(char*));

根本没有意义。我不确定你想在那里完成什么。删除该行。

为了能够使用:

for (i=0; i<41; i++)
        strcpy((*current).args[i], args[i]);

您需要为(*current).args 的每个元素分配内存。这是一种方法:

for (i=0; i<41; i++)
{
   int len = strlen(args[i]);
   (*current).args[i] = malloc(len+1);
   strcpy((*current).args[i], args[i]);
}

【讨论】:

  • 有道理,我认为原始行是为整个数组分配空间。您的解决方案分别为每个指针分配空间。谢谢你的帮助,效果很好!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-18
相关资源
最近更新 更多