固定行数的动态分配二维数组scanf输入错误排查求助
解决动态二维数组输入的编译错误问题
你遇到的编译错误核心原因非常直接——scanf函数的格式字符串和地址参数之间漏掉了逗号!这是个典型的语法小失误,但编译器会把它解析成非法的表达式,所以抛出了那串报错。
先看你出错的关键行:
scanf("%ld" &buckets[no_of_rows][c]);
正确写法应该在"%ld"和&buckets[no_of_rows][c]之间加上逗号:
scanf("%ld", &buckets[no_of_rows][c]);
除了这个语法错误,你的代码还有几个值得优化和注意的细节,我一起整理成可运行的完整版本:
修正后的完整代码
#include <stdio.h> #include <stdlib.h> int main() { // 固定行数为3的动态二维数组,每一行是一个long类型指针 long *buckets[3]; int no_of_cols, no_of_rows, c; // 数组大小用int更合理,避免long类型的不必要开销 printf("number of elements in each column: "); scanf("%d", &no_of_cols); // 为每一行分配内存,同时检查内存分配是否成功 for (no_of_rows = 0; no_of_rows < 3; no_of_rows++) { buckets[no_of_rows] = calloc(no_of_cols, sizeof(long)); // 检查calloc是否成功分配内存,避免空指针操作 if (buckets[no_of_rows] == NULL) { fprintf(stderr, "Memory allocation failed for row %d\n", no_of_rows); return 1; } } int total_elements = no_of_cols * 3; printf("input %d elements: ", total_elements); // 输入矩阵元素 for (no_of_rows = 0; no_of_rows < 3; no_of_rows++) { for (c = 0; c < no_of_cols; c++) { scanf("%ld", &buckets[no_of_rows][c]); // 补上缺失的逗号 } } // 验证输入结果(可选) printf("\nYour input matrix:\n"); for (no_of_rows = 0; no_of_rows < 3; no_of_rows++) { for (c = 0; c < no_of_cols; c++) { printf("%ld ", buckets[no_of_rows][c]); } printf("\n"); // 释放每一行的动态内存,避免内存泄漏 free(buckets[no_of_rows]); } return 0; }
额外的细节说明
- 内存分配检查:calloc可能因内存不足分配失败,返回NULL,一定要加检查,否则后续操作空指针会导致程序崩溃。
- 变量类型选择:数组的行数、列数用
int足够,long适合更大范围的整数,这里用它纯属浪费内存。 - 内存释放:动态分配的内存必须手动释放,上面的代码在打印完每一行后就释放了对应内存,你也可以在所有操作完成后统一释放。
- 变量初始化:虽然你的代码里变量在使用前都被赋值了,但养成初始化变量的习惯能避免很多潜在的未定义行为。
这样修改后,程序就能正常接收用户输入并存储到动态二维数组中了。
内容的提问来源于stack exchange,提问作者Neo
相关产品推荐
相关产品推荐

