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
OPT[i]before usingstrcpyon it. Also, you need to add error checking. For example, in case no valid free entry is found inOPT.