我對const char
指針感到困惑。字符指針的地址變化
下面是代碼:
int main()
{
const char map[12][24];
char fileName[] = "map1.txt";
const char * mPtr;
mPtr = map;
printf("%d %d \n", mPtr, map);
load_map(fileName, map);
printf("%d %d \n", mPtr, map);
return 0;
}
這裏是load_map()
功能代碼:
bool load_map(char * fileName, char * map)
{
FILE * fptr;
char c;
int count = 0;
fptr = fopen(fileName, "r");
if(fptr == NULL) {
printf("Fail to read map \n");
return false;
}
do {
c = fgetc(fptr);
*(map + count++) = c;
if (count % 23 == 0) continue;
*(map + count++) = ' ';
} while(c != EOF);
fclose(fptr);
}
我的問題是執行
mPtr = map;
,當他們正好有相同的內存地址,但執行load_map()
功能後 mptr
的值已更改。
但是在該功能中,我沒有參考mptr
。發生什麼事?
使用'%p'而不是'%d'來打印指針,否則你會得到警告 – phschoen
事實上,根據C的實現,你可能甚至不打印mptr的內容。你應該在你的問題中包含實際的輸出,因爲這可以提供一些見解。 –