我对char指针有一种奇怪的行为。根据我对指针的了解,我应该能够通过向其添加一个指向我的char指针的每个指向字符,因为char是一个字节。但是,似乎并非如此,使用增量运算符+ =,++,甚至将char指针设置为等于自身加一。这些都没有像人们想象的那样影响指针。如果我只是在我的char指针中添加一个数字或变量,它就会像人们期望的那样完美地工作。
这不起作用:
void getNextWord(FILE * pFile)
{
char * w = (char *)malloc(MAX_WORD_SIZE * sizeof(char *));
char c;
while(c != ' ')
{
c = fgetc(pFile);
if(c != ' ')
{
*(w++) = c;
}
}
*(w++) = '\0';
printf("%s",w);
}
这确实有效:
void getNextWord(FILE * pFile)
{
char * w = (char *)malloc(MAX_WORD_SIZE * sizeof(char *));
int i = 0;
char c;
while(c != ' ')
{
c = fgetc(pFile);
if(c != ' ')
{
*(w + i) = c;
i++;
}
}
*(w + i) = '\0';
printf("%s",w);
}
有谁知道为什么会这样?
答案 0 :(得分:5)
在第一种情况下,每次添加角色时都会增加w,因此它总是指向您添加的最后一个角色。当你打印它时,它指向尚未初始化的内存。
char *s = w; // Save a pointer to the beginning of the string.
while (c != ' ') {
c = fgetc(pFile);
if (c != ' ') {
// Store the character at w, then increment w
// to point at the next available (unused) location.
*(w++) = c;
}
}
// Null-terminate the string, and increment w again.
// Now it points one location beyond the end of the string.
*(w++) = '\0';
// This will print whatever happens to be in the uninitialized memory
// at w. It will continue to print until it encounters a null character
// (or "illegal" memory, at which point it will crash).
printf("%s", w);
// This will work as expected because it prints the characters that
// have been read.
printf("%s", s);
// This will also work because it "resets" w
// to the beginning of the string.
w = s;
printf("%s", w);