简体   繁体   English

为什么当我在 C 中打印时,二维数组会重复结果?

[英]Why 2d array repeats the results when i print it in C?

Here the code i wrote:这是我写的代码:

#include <stdio.h>
void ReadData_and_Print(int r, int c, double pin[r][c]);    
int main(){
    int p[0][0];
    ReadData_and_Print(0,0,p[0][0]);
}

void ReadData_and_Print(int r, int c, double pin[r][c])
        {
        int i=0,j=0;
        printf("give rows:");
        scanf("%d",&r);
        printf("give columns");
        scanf("%d",&c);

        for (i=0;i<r;i++)
        {
            for (j=0;j<c;j++)
            {
                printf("give number:");
                scanf("%d",&pin[i][j]);
            }
        }


        for (i=0;i<r;i++)
        {
            for (j=0;j<c;j++)
            {

        printf("%d ",pin[i][j]);
            }
        }

The output: output:

give rows2
give columns3
give number1
give number2
give number3
give number4
give number5
give number6
3 4 5 6 3 4 5 6

When i give 1 2 3 4 5 6 the results is 3 4 5 6 3 4 5 6.Ι should expect 1 2 3 4 5 6. I know is very simple question but its bother me.I do not rule out that is lack of my knowledge about arrays and for.I did research but i cant find the solution.当我给出 1 2 3 4 5 6 时,结果是 3 4 5 6 3 4 5 6。我应该期待 1 2 3 4 5 6。我知道这是一个非常简单的问题,但它困扰着我。我不排除缺乏根据我对 arrays 和 for.I 的了解。我进行了研究,但找不到解决方案。 Thanks in advance.提前致谢。

You created an array with a dimension of 0. This is a constraint violation in the declaration of an array and therefore invokes undefined behavior .您创建了一个维度为 0 的数组。这违反了数组声明中的约束,因此会调用未定义的行为

You don't need to define the array in main or pass it to ReadData_and_Print .您无需在main中定义数组或将其传递给ReadData_and_Print Just declare r and c as local to ReadData_and_Print , read their values, then declare the array after that with those values as the size.只需rc声明为ReadData_and_Print的本地,读取它们的值,然后使用这些值作为大小声明数组。

    int r, c;
    printf("give rows:");
    scanf("%d",&r);
    printf("give columns");
    scanf("%d",&c);

    int pin[r][c];
    ...

Welcome to the world of C!欢迎来到 C 的世界!

Allow me to give an answer first:请允许我先给出一个答案:

#include <stdio.h>
#include <stdlib.h>

void ReadData_and_Print(int r, int c, int ** pin){
    int i = 0 ,j = 0;

    // Get rows and columns
    printf("give rows:");
    scanf("%d",&r);
    printf("give columns");
    scanf("%d",&c);

    // Initialize the pin array
    pin = (int **) malloc(sizeof(int*) * r);
    for (i=0; i<r; i++){
        pin[i] = (int *)malloc(sizeof(int) * c);
    }

    // Scan all the number and store them
    for (i=0; i<r; i++){
        for (j=0; j<c; j++){
            printf("give number:");
            scanf("%d",&pin[i][j]);
        }
    }


    // Print them all
    for (i=0;i<r;i++){
        for (j=0;j<c;j++){
            printf("%d ",pin[i][j]);
        }
    }
}

int main(){
    int ** p = NULL;
    ReadData_and_Print(0, 0, p);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM