C语言指针未初始化错误:如何解决本地指针变量p的问题

在你的代码中,你在循环内部使用了未初始化的本地指针变量 p,这会导致程序出现错误。为了解决这个问题,你需要将 Base* p = NULL; 移动到 while (x != 0) 循环的外部,确保 p 在每次循环迭代中都被正确初始化。

以下是修改后的代码:cvoid DecimaltoN(Base* l) { Base* p = NULL; // 将初始化移到循环外部 Base* t; char q[50]; static char Start[] = 'Start'; static char End[] = 'End'; printf('输入Start开始进制转换,输入End结束:'); gets_s(q); while (strcmp(q, Start) != 0) { if (strcmp(q, End) == 0) { printf('你取消了进制转换!'); break; } printf(' 输入错误!输入Start开始进制转换:'); memset(q, 0, sizeof q); gets_s(q); } while (strcmp(q, End) != 0) { int n, x, i, k; k = 0; char z = 'A'; printf(' 输入要转换的数值与转换的进制:'); scanf('%d %d', &x, &n); while (x != 0) { p = (Base*)malloc(sizeof(Base)); // 在每次循环迭代中分配内存 i = x % n; p->record = i; if (i > 9) { p->record += z - 10; } else { p->record += '0'; } p->top = l; l = p; x = x / n; k++; } t = l; if (t == NULL) { printf('错误!!'); } else { printf(' 进制转换后:'); for (i = 0; i < k; i++) { printf('%c', t->record); t = t->top; } } printf(' 输入要转换的值与转换的进制或者输入End结束进制转换:'); l = NULL; free(p); // 释放之前分配的内存 memset(q, 0, sizeof q); gets_s(q); gets_s(q); }}

代码解释:

  1. Base* p = NULL; 移动到循环外部: 确保 p 在每次进入 while (x != 0) 循环时都被初始化为 NULL。2. 在循环内部为 p 分配内存: 在每次循环迭代中,使用 malloc() 函数为 p 分配新的内存空间。 3. 释放已分配的内存: 在循环结束后,使用 free(p) 释放为 p 分配的内存,防止内存泄漏。

通过将指针变量 p 的初始化移到循环外部,并确保每次使用前都分配内存,可以避免使用未初始化指针变量导致的程序错误。


原文地址: https://www.cveoy.top/t/topic/btEY 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录