C语言如何通过用户输入的两个数值设置二维数组的维度
问题修复方案
报错翻译
你遇到的报错翻译为:
表达式应为指向对象的指针类型,但它当前的类型是int
报错原因
你将pos定义为了单个int类型的普通变量,自然无法使用[x][y]的二维下标语法做数组访问,这是触发报错的直接原因。
另外你的代码还存在其他几处问题:
- 存储绘图符号的
sign数组长度仅为1,存储字符串时没有预留字符串结束符\0的位置,会触发内存越界 - 打印画板的循环逻辑冗余,外层循环每轮会先多打印1个
board字符,最终输出的列数会比用户输入的多1 - 你没有按用户输入的绘图符号渲染画板,仍在使用固定的
'O'字符
实现动态长度二维数组的方案
C语言实现用户输入维度的二维数组共有两种常用方案:
方案1:C99可变长数组(VLA,写法最简单)
如果你的编译器支持C99及以上标准(现在绝大多数常用编译器都支持),可以直接在获取到x、y的取值后定义对应长度的二维数组,不需要手动管理内存。
修改后的完整代码如下:
#include<stdio.h> int main() { int x, y; // 预留字符串结束符存储空间 char sign[2]; // 设置列数 printf("enter the number of columns:\n "); scanf_s("%d", &x); // 设置行数 printf("enter the number of rows: \n"); scanf_s("%d", &y); // 设置绘图符号 printf("enter the sign you want to draw with: \n"); scanf_s("%s", sign, sizeof(sign)); // 定义动态长度的二维画板数组 char pos[y][x]; // 初始化画板为用户选择的绘图符号 for(int i=0; i<y; i++) { for(int j=0; j<x; j++) { pos[i][j] = sign[0]; } } // 打印画板 for (int count = 0; count < y; count++) { for (int count2 = 0; count2 < x; count2++) { printf("%c", pos[count][count2]); } printf("\n"); } return 0; }
方案2:动态内存分配(兼容旧标准)
如果需要兼容C89等不支持可变长数组的旧标准,可以用malloc手动申请堆内存实现动态二维数组,使用完成后需要手动释放内存避免泄漏。
示例代码如下:
#include<stdio.h> #include<stdlib.h> int main() { int x, y; char sign[2]; printf("enter the number of columns:\n "); scanf_s("%d", &x); printf("enter the number of rows: \n"); scanf_s("%d", &y); printf("enter the sign you want to draw with: \n"); scanf_s("%s", sign, sizeof(sign)); // 先申请行指针数组 char** pos = (char**)malloc(y * sizeof(char*)); for(int i=0; i<y; i++) { // 每行申请对应长度的内存 pos[i] = (char*)malloc(x * sizeof(char)); for(int j=0; j<x; j++) { pos[i][j] = sign[0]; } } // 打印画板 for (int count = 0; count < y; count++) { for (int count2 = 0; count2 < x; count2++) { printf("%c", pos[count][count2]); } printf("\n"); } // 释放内存 for(int i=0; i<y; i++) { free(pos[i]); } free(pos); return 0; }
内容的提问来源于stack exchange,提问作者Punz
相关产品推荐
相关产品推荐

