开发者

How to use array of pointers?

开发者 https://www.devze.com 2023-03-06 13:31 出处:网络
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.

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>开发者_Python百科;
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?


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;
}


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.


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));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号