C语言指针地址存值异常:函数内赋值成功main函数无法获取值
问题诊断与修复方案
核心错误点
- 参数类型不匹配:main中定义的
lines/words/chars本身是int*类型,取地址后为int**二级指针,但wc函数的形参声明为int*一级指针,类型完全不匹配,所有内存操作均为非法访问。 - 形参值传递特性:C语言参数为值传递,wc函数内部修改
nchars/nlines/nwords这些形参本身的地址,修改的只是wc栈上的临时副本,malloc得到的地址无法同步到main的实参指针中。 - 语法逻辑错误:wc函数声明返回
bool类型但无return语句,属于未定义行为;printf打印时直接传入指针变量,未做解引用,输出的是内存地址而非存储的数值。 - 冗余动态分配:仅需存储3个int类型的统计值,完全不需要动态内存分配,直接通过普通int变量的地址写入即可,额外malloc只会造成内存泄漏风险。
修复方案
最优方案:移除冗余动态分配
#include <stdio.h> #include <stdbool.h> bool wc(int* nlines, int* nwords, int* nchars) { int lines = 5, chars = 6, words =7; *nchars = chars; *nlines = lines; *nwords = words; return true; } int main() { int chars, words, lines; bool res = wc(&lines, &words, &chars); printf("%d %d %d\n", chars, lines, words); return 0; }
保留动态分配的修正写法(仅用于理解二级指针逻辑,不推荐生产环境使用)
#include <stdio.h> #include <stdbool.h> #include <stdlib.h> // 形参声明为二级指针,接收main中指针变量的地址 bool wc(int** nlines, int** nwords, int** nchars) { int lines =5, chars=6, words=7; *nchars = malloc(sizeof(int)); **nchars = chars; *nlines = malloc(sizeof(int)); **nlines = lines; *nwords = malloc(sizeof(int)); **nwords = words; return true; } int main() { int *chars, *words, *lines; bool res = wc(&lines, &words, &chars); // 解引用拿到实际存储的数值 printf("%d %d %d\n", *chars, *lines, *words); // 释放动态分配的内存避免泄漏 free(chars); free(words); free(lines); return 0; }
内容的提问来源于stack exchange,提问作者noor napso
相关产品推荐
相关产品推荐

