C语言程序设计:初始化与数字1,2,3 ...等一个二维数组 [英] C Programming: Initialize a 2D array of with numbers 1, 2, 3...etc
问题描述
我无法创建用户定义的大小的二维数组,有数字1,2,3.etc。
如果用户选择例如: A = 2,B = 2
,程序产生:
3 43 4
而不是:
1 23 4
我的计划是这样的:
的#include<&stdio.h中GT;诠释的main()
{
INT A = 0;
INT B = 0;
int数组[A] [B]。
INT行,列;
诠释计数= 1;/ *用户输入* /
的printf(请输入a和b \\ n);
scanf函数(%D,&安培;一,和b);/ *创建数组* /
为(行= 0;&行LT; A;排++)
{
为(柱= 0;柱&下; B;柱++)
{
数组[行] [列] =计数;
算上++;
}
}/ *打印数组* /
为(行= 0;&行LT; A;排++)
{
为(柱= 0;柱&下; B;柱++)
{
的printf(%d个,数组[行] [列]);
}
的printf(\\ n);
} 返回0;
}
INT A,B;
变量 A
和 B
是未初始化的,其价值是由C语言未定
int数组[A] [B]。
您声明其中有[A,B]大小的数组。问题是,a和b都是不确定的,使用它们在这一点上是未定义的行为。
scanf函数(%D,&安培;一,和b);
你 A
和 B
值 - 但阵列
是一样的!
简单的解决方案:试图把数组声明后 scanf函数
。你的编译器可能会允许它(我认为C99要求这样做)。
I am having trouble creating a 2D Array of a size defined by the user, with numbers 1, 2, 3.etc.
If the user chooses for example: a = 2 and b = 2
, the program produces:
3 4
3 4
instead of:
1 2
3 4
My program looks like:
#include <stdio.h>
int main()
{
int a = 0;
int b = 0;
int Array[a][b];
int row, column;
int count = 1;
/*User Input */
printf("enter a and b \n");
scanf("%d %d", &a, &b);
/* Create Array */
for(row = 0; row < a; row++)
{
for(column = 0; column <b; column++)
{
Array[row][column] = count;
count++;
}
}
/* Print Array*/
for(row = 0; row<a; row++)
{
for(column = 0; column<b; column++)
{
printf("%d ", Array[row][column]);
}
printf("\n");
}
return 0;
}
int a, b;
variables a
and b
are uninitialized and their value is undetermined by C language
int Array[a][b];
You declare an array which has [a,b] size. The problem is that a and b are undetermined and using them at this point is undefined behavior.
scanf("%d %d", &a, &b);
you get a
and b
values -- but the Array
remains the same!
Simplest solution: try to put Array declaration after scanf
. Your compiler may allow it (I think C99 is required to do so).
这篇关于C语言程序设计:初始化与数字1,2,3 ...等一个二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!