Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

C Programming: Initialize a 2D array of with numbers 1, 2, 3...etc

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 
");
    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("
");
    }

    return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...