[英]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
我沒想到的是pathArray [pathIndex] = nextFile; 將nextFile的地址分配給該索引,因此每當nextFile進行操作時,整個數組都會更改。 我是C語言的新手,嘗試了很多事情,發現在獲取整個文件名時遇到了很多問題(許多文件名中都包含空格,因此應該在用戶按下回車鍵之前將其讀取,並且以上是我發現防止文件名在第一個空格處被切斷的方法。
我還嘗試添加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手冊頁:
strdup()函數返回一個指向新字符串的指針,該字符串與s字符串重復。 新字符串的內存是通過malloc(3)獲得的,可以通過free(3)釋放。
注意:您需要釋放新創建的副本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.