Nam
Nam

Reputation: 63

insert char array elements in an array consists of char array

I want to insert a string to an array of strings and got a problem...I can't figure out what's the reason for it.

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

My Output:

(null)
Segmentation fault: 11

Upvotes: 0

Views: 58

Answers (2)

selbie
selbie

Reputation: 104514

This is the issue:

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

You are attempting to copy to a NULL pointer. You need to allocate memory for the string copy to be placed into OPT.

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

Or alternatively:

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

Now, let's cleanup your entire function to something more consice and readable:

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

Upvotes: 1

ammasum
ammasum

Reputation: 128

C doesn't support multiple string in char array. Instead of you have to use 2d array to put multiple string in array.

Upvotes: 0

Related Questions