我試圖抓住的函數的參數之一,它店在字符數組。
與您的代碼的問題是,你沒有一個字符數組在其中存儲複製的說法。你有什麼是一個指針。您必須分配用於複製參數的存儲。或者,您可以使rootdir
成爲數組而不是指針,但您必須小心以防止副本溢出固定大小的數組。
分配存儲
bb_data->rootdir = malloc(strlen(argv[argc - 2]) + 1); // +1 is for the NULL
製作ROOTDIR陣列
#include <limits.h>
#include <stddef.h>
#include <stdlib.h>
...
struct bb_state {
FILE *logfile;
char rootdir [PATH_MAX];
};
struct bb_state *bb_data;
size_t len;
len = strlen(argv[argc - 2]);
if (len >= PATH_MAX) {
// Argument is too long.
fprintf(stderr, "Argument is too long: %s\n", argv[argc - 2]);
return EXIT_FAILURE;
}
bb_data = malloc(sizeof(struct bb_state));
strcpy(bb_data->rootdir, argv[argc - 2]);
有必要確保指針('bb_data-> rootdir')指向的區域。 – BLUEPIXY
你檢查過'bb_data-> rootdir'的大小嗎?在'char * strcpy(char * destination,const char * source)'中:爲了避免**溢出**,** destination **指向的數組的大小應足夠長以包含與**相同的C字符串源**(包括終止空字符),並且不應該在內存中與源重疊。 –