【发布时间】: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