简体   繁体   中英

How can I assign elements to a const char * array from a normal char array in a loop?

const char * pathArray[50];
char nextFile[35];

while(lastFile == 0) {
    file_descriptor = open(nextFile, O_RDWR);

    if (file_descriptor == -1){
        printf("Sorry, but %s could not be opened", nextFile);  
        exit(1);
    }

    nread = read (file_descriptor, buffer, 512);
    close(file_descriptor);

    if(strstr(buffer, "LAST_FILE") != NULL){
        lastFile++;
        break;
    }

    printf("CURRENT FILE: %s\n", nextFile);
    printf("\n NEXT FILE:");
    scanf(" %[^\n]", nextFile); 
    pathIndex++;
    pathArray[pathIndex] = nextFile;

    for(i = 0; i < pathIndex; i++) { 
        printf("%d: %s\n", i, pathArray[i]);        
    }
} //end while

What I hadn't anticipated is that pathArray[pathIndex] = nextFile; assigns the address of nextFile to that index, so the entire array gets changed whenever nextFile does. I'm very new to C and have tried a lot of things and found a lot of problems getting the whole file name in (many of the file names have spaces in them so it's supposed to be read until the user hits enter, and the above was the way I found to prevent the file name from being cut off at the first space).

I also tried adding a char * otherArray[50] so that I could use strcpy, but changing my assignment to:

    strcpy(otherArray[pathIndex], nextFile);
    pathArray[pathIndex] = otherArray[pathIndex];

causes a segmentation fault. Can anyone help?

I believe you are looking for something like this

char *pathArray[50];
char nextFile[35];
int pathIndex = 0;

// Do something to read into nextFile?
// create new mem for string and assign pointer to new string in your array
pathArray[pathIndex++] = strdup(nextFile); 

The reason it is seg faulting is due to not allocating any memory for the string inside your array.

From strdup man page:

The strdup() function returns a pointer to a new string which is a duplicate of the string s. Memory for the new string is obtained with malloc(3), and can be freed with free(3).

Note: you are required to free the newly created copy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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