char 指针 - 如何调试此代码?

标签 c variables pointers char

#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/

相关文章:

php - 在变量中存储 PHP 语法

javascript - 如何在 JavaScript Node.js 中将函数分配给全局变量?

python - 第二次调用函数,仅进行微小的更改

pointers - Golang 编辑从 main() 到函数的 struts 数组

c - C 中带索引的指针和数组

c - OpenGL:从读取文件的 while 循环中调用 glutPostRedisplay()

c++ - Ruby 模仿 C 整数数据类型和 union

c - 释放指向其他结构的结构中的指针

c - 我对 n*log(N) Big O 的样子很感兴趣

c - Linux 中的周期性任务