Giorgosks94
Giorgosks94

Reputation: 15

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:

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. Thanks in advance.

Upvotes: 0

Views: 42

Answers (2)

Ginda Chen
Ginda Chen

Reputation: 81

Welcome to the world of 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);
}

Upvotes: 1

dbush
dbush

Reputation: 223699

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.

You don't need to define the array in main or pass it to 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.

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

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

Upvotes: 2

Related Questions