在由char数组组成的数组中插入char数组元素

时间:2019-11-28 18:48:10

标签: c arrays string insert

我想在一个字符串数组中插入一个字符串并遇到问题...我不知道是什么原因。

char* OPT[100]; 

void setOpt(char* ele){
    char* beginning = ele;      //start of index option
    int size = sizeOpt(ele);    //length of option
    char result[size];          //our OPTION

    //go to the first character of option
    while(*beginning != 0 && ((*beginning < 'a' || *beginning > 'z') && (*beginning < 'A' || *beginning > 'Z'))){
    ++beginning;
    }

    strncpy(result, beginning, size);       //get OPTION
    int i = 0;                              //insert at index
    while(OPT[i] != NULL){
        ++i;                
    }
    printf("%s\n", OPT[i]); 
    strcpy(OPT[i], result);                 //insert in array of OPTIONS
}

int main(int argc, char* argv[]){
    char* some[] = {"ls" , ".", "-maxdepth=n", "-something=123"};

    setOpt(some[2]);
   setOpt(some[3]);
   return 0;
}

我的输出:

(null)
Segmentation fault: 11

2 个答案:

答案 0 :(得分:1)

这是问题所在

strcpy(OPT[i], result);                 //insert in array of OPTIONS

您正在尝试复制到NULL指针。您需要为将字符串副本放入OPT分配内存。

OPT[i] = strdup(result);                 //insert in array of OPTIONS

或者:

OPT[i] = (char*)malloc(strlen(result)+1);
strcpy(OPT[i], result);

现在,让我们将整个功能清理得更简洁易读:

int isLetter(char c) {
    return (((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')));
}

void setOpt(const char* ele) {

    const unsigned int maxentries = sizeof(OPT) / sizeof(OPT[0]);
    unsigned int i = 0;
    while (i < maxentries && OPT[i]) {
        i++;
    }

    if (i < maxentries)
    {
        const char* result = ele;
        while (*result && !isLetter(*result)) {
            result++;
        }

        if (*result) {
            OPT[i] = (char*)malloc(strlen(result) + 1);
            strcpy(OPT[i], result);
        }
    }
}

答案 1 :(得分:0)

C在char数组中不支持多个字符串。而不是必须使用2d数组将多个字符串放入数组中。