简体   繁体   English

字符指针数组的分段错误

[英]Segmentation Fault with Character Pointer Array

I am fairly new to C and have been having a lot of difficulty trying to copy the values of an array of pointers to strings.我对 C 相当陌生,并且在尝试将指针数组的值复制到字符串时遇到了很多困难。 I have created a struct that contains such a pointer array (part of an implementation of a doubly linked list)我创建了一个包含这样一个指针数组的结构(双向链表实现的一部分)

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

When I want to add a node, I have been using the following method当我想添加节点时,我一直在使用以下方法

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

I think the root of my problem is in how I am allocating space for the pointers in the new node, but I haven't been able to figure out what I was doing wrong.我认为我的问题的根源在于我如何为新节点中的指针分配空间,但我一直无法弄清楚我做错了什么。 As it stands, I get a Segmentation Fault (core dumped) as soon as the strcpy line is reached.就目前而言,一旦到达 strcpy 行,我就会收到分段错误(核心已转储)。

Any idea what Im doing wrong?知道我做错了什么吗?

The line线

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

does not make sense at all.完全没有意义。 I am not sure what you were trying to accomplish there.我不确定你想在那里完成什么。 Remove that line.删除该行。

In order to be able to use:为了能够使用:

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

you need to allocate memory for each element of (*current).args .您需要为(*current).args每个元素分配内存。 Here's one way:这是一种方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM