【问题标题】:C Beginner - Copying a char *array to another char *arrayC 初学者 - 将一个 char *array 复制到另一个 char *array
【发布时间】:2014-01-22 17:49:57
【问题描述】:

我已经为此苦苦挣扎了很长时间。 基本上,我需要将一个 char 指针数组复制到另一个 char 指针数组。

现在,我有这个功能:

void copyArray(char *source[], char *destination[]) {
    int i = 0;

    do {
        destination[i] = malloc(strlen(source[i]));
        memcpy(destination[i], source[i], strlen(source[i]));
    } while(source[i++] != NULL);
}

这会导致分段错误。有人可以帮忙吗?

谢谢!

编辑:示例程序

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

// Copy the contents of one array into another
void copyArray(char *source[], char *destination[]){
    // printf("In copy array");
    int i = 0;

    do {
        destination[i] = malloc(strlen(source[i]));
        memcpy(destination[i], source[i], strlen(source[i]));
    } while(source[i++] != NULL);
}

void addToHistory(char *history[][40], char *args[]){
    int i;
    for(i = 1; i < 10; i++){
        copyArray(history[i], history[i-1]);
    }
    i = 0;
    copyArray(args, history[0]);
}

int main(void){
    char *history[10][40];
    char *args[40];

    history[0][0] = NULL;

    args[0] = "ls";
    args[1] = NULL;

    addToHistory(history, args);
}

【问题讨论】:

  • 你确定数组 source[] 有一个最终的 NULL 值吗?
  • 您尝试过使用调试器吗?
  • 你能展示一个完整的(但很小的)示例程序来演示这个问题吗?
  • 出于我的目的,我知道 source 将以最终的 NULL 值结尾(这是我的程序中解析字符串的方式)。我正在开发一个简单的 shell 程序,并上传了一个小的测试代码 sn-p..
  • 请检查你的qn的答案,这里:stackoverflow.com/questions/36565328/…

标签: c


【解决方案1】:
  1. 确保source 数组中的最后一个元素是NULL,然后再将其传递给copyArray

  2. copyArray 中,使用while 而不是do,并仅在循环的末尾增加i

您可以在函数copyArray 中简单地将i++ 更改为++i

但是如果source数组中传递给这个函数的第一个元素是NULL,它就会崩溃。

【讨论】:

    【解决方案2】:

    我认为你有一个错误:

    do {
        destination[i] = malloc(strlen(source[i]));
        memcpy(destination[i], source[i], strlen(source[i]));
    } while(source[i++] != NULL);
                   ^^^
    

    你检查我是否 NULL 之后你已经使用它,然后结束循环。尝试将其替换为

    } while (source[++i] != NULL);           // or while (source[++i]), for short
    

    您可以尝试在每次迭代后记录一条短消息,以查看代码错误的位置。

    编辑:您使用memcpy()(不会复制终止的'\0')而不是strcpy()(会)有什么原因吗?

    (@wildplasser 的注意事项:我相信 strdup() 可能不是标准 C)。

    【讨论】:

      【解决方案3】:
      void copyArray(char *source[], char *destination[]) {
      
          while ((*destiantion = *source)) {
              *destination++ = strdup( *source++ );
          }
      }
      

      顺便说一句:将目的地作为第一个参数是很常见的,就像在strcpy()中一样

      void copyArray(char *destination[], char *source[]) { ... }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-27
        • 2014-09-22
        • 2015-06-07
        • 2017-08-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多