#include <stdio.h>
int main(){
char *p, *initial;
int c, in=0;
for(initial=p; (c = getchar()) != EOF; p++, in++)
*p = c;
for(int i=0; i<in; i++)
printf("%p = %c\n", initial, *initial++);
}
对于像 hello hai
这样的输入,程序给出不完整的输出:
0028FF29 = h
0028FF2A = e
0028FF2B = l
0028FF2C = l
0028FF2D =
0028FF2E =
0028FF2F =
0028FF30 =
0028FF31 =
它适用于小文本,但不适用于大文本。
最佳答案
未定义的行为。您没有将 p
设置为指向任何有效的内存位置。所以 *p = c
并不是一个定义明确的程序。
您可以让p
指向固定大小的缓冲区(如果您知道输入永远不会超过一定数量的字符):
char buff[MAX_SIZE];
char *p = buff;
或者使用动态内存分配:
char *p = malloc(INITIAL_SIZE);
size_t current_size = INITIAL_SIZE;
// Later
if (p - initial == current_size) {
char *buff_new = realloc(initial, current_size * 2);
if (buff_new) {
initial = buff_new;
p = initial + current_size;
current_size *= 2;
}
else
// should probably abort here, the program is out of memory. Bad bad bad.
}
关于char 指针 - 如何调试此代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41589448/