1

I wrote a C program to create an array of pointers and each of the individual pointers will in turn be separate arrays(somewhat like a 2D array). I wrote the following C code but it doesn't work.

#include<stdlib.h>
#include<conio.h>
int main(void)
{
    int rows=5,cols = 5;
    int *a[100];
    int i = 0;
    int j;
    int k = 0;
    int b[100];
    while(i<rows)
    {
        printf("\nEnter the %d row: ",i);
        for(j=0;j<cols;j++)
            scanf("%d",&b[j]);

        a[k++] = b;
        i = i + 1;
    }
    k = k-1;
    for(i=0;i<=k;i++){
        for(j=0;j<cols;j++){
            printf("%d  ",a[i][j]);
        }
    }              

    getch();
    return 0;
}

I want something like a 5*5 matrix structure but I want to manipulate each row as if they were a one dimensional array . Can someone tell me how to do that?

1
  • 1
    ...as an what? I think your question is truncated. Commented May 15, 2011 at 15:46

3 Answers 3

2

The bug is here:

a[k++] = b;

I assuming you are attempting to make a copy of b and add it to a, but you are really only adding another reference to b.

Try this instead:

// int b[100]; // Delete this!
while(i<rows)
{
    int *b = calloc(cols, sizeof(int)); // Replacement for int b[100] 
    printf("\nEnter the %d row: ",i);
    for(j=0;j<cols;j++)
        scanf("%d",&b[j]);

    a[k++] = b; // Now it's safe to do this, because `b` is a different array each time
    i = i + 1;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Each of your row pointers points to the same row! Your program overwrites row 0 with row 1 and then row 1 with row 2, etc. You need a separate array for each row.

1 Comment

I got it every time a new array b is entered the old one is lost .The problem occurs when thenumber of row increases.Moreover ,I don't know the number of rows in advance,it will be supplied to me in run time by the user. Then this approach becomes infeasible.Can you suggest a way to solve thias
0

What's wrong with int a[5][5];? But if you want to dynamically control the dimensions, start with:

int rows = 5, cols = 5;
int** a;
int i;

a = malloc(rows * sizeof(*a));
for(i = 0; i < rows; i++)
    a[i] = malloc(cols * sizeof(**a));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.