gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 18:54:36 25 4
gpt4 key购买 nike

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

我没想到的是pathArray[pathIndex] = nextFile;将 nextFile 的地址分配给该索引,因此每当 nextFile 发生变化时,整个数组都会发生变化。我对 C 很陌生,尝试了很多东西,发现在获取整个文件名时存在很多问题(许多文件名中都有空格,因此应该在用户按 Enter 之前读取它,并且以上是我发现的防止文件名在第一个空格处被截断的方法)。

我还尝试添加 char * otherArray[50] 以便我可以使用 strcpy,但将我的分配更改为:

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

导致段错误。有人可以帮忙吗?

最佳答案

我相信您正在寻找这样的东西

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

出现段错误的原因是没有为数组内的字符串分配任何内存。

来自 strdup 手册页:

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).

注意:您需要释放新创建的副本。

关于c - 如何在循环中将普通 char 数组中的元素分配给 const char * 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29955301/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com