简体   繁体   English

如何在循环中将元素从普通char数组分配给const char *数组?

[英]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; 我没想到的是pathArray [pathIndex] = nextFile; assigns the address of nextFile to that index, so the entire array gets changed whenever nextFile does. 将nextFile的地址分配给该索引,因此每当nextFile进行操作时,整个数组都会更改。 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). 我是C语言的新手,尝试了很多事情,发现在获取整个文件名时遇到了很多问题(许多文件名中都包含空格,因此应该在用户按下回车键之前将其读取,并且以上是我发现防止文件名在第一个空格处被切断的方法。

I also tried adding a char * otherArray[50] so that I could use strcpy, but changing my assignment to: 我还尝试添加char * otherArray [50],以便可以使用strcpy,但是将我的分配更改为:

    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: 从strdup手册页:

The strdup() function returns a pointer to a new string which is a duplicate of the string s. strdup()函数返回一个指向新字符串的指针,该字符串与s字符串重复。 Memory for the new string is obtained with malloc(3), and can be freed with free(3). 新字符串的内存是通过malloc(3)获得的,可以通过free(3)释放。

Note: you are required to free the newly created copy. 注意:您需要释放新创建的副本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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