c - 在c中重新填充二维数组

标签 c arrays pointers

我有两个大小相同的二维数组“a”,“b”(空数组),我必须更改“a”,因为某个函数将其新值保存在“b”中,然后我必须根据相同的函数更改新值,因此程序会将 b 的新值保存到 a 中,然后返回到 a 中。 当打印数组时,仅打印前两个!

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MSIZE 10

void new_gen(char * a[MSIZE],int s,char** b);      /*the function we talked                     about*/
void print_m(char** b,int s);   /*prints matrix*/
void cpy_m(char** b, char** a, int s);

int main()
{
    int Size, gen, i, j;
    printf("Enter number of generations\t");   
    scanf("%d", &gen);
    printf("\nEnter size of the matrix (max size is %d and min is 2)\t", MSIZE);
    scanf("%d", &Size);
    char **m = (char**) malloc(Size*sizeof(char*));
    for (i=0; i<Size; i++)
    {
        m[i] = (char*) malloc(Size*sizeof(char));
    }
    printf("Enter matrix of first generation\n");
    for (i=0; i<Size; i++)  {
        for (j=0; j<Size; j++)  {
            scanf(" %c", &m[i][j]);
        }
    }
    print_m(m, Size);

    for (i=1; i<gen; i++)
    {
        char **n = (char**) malloc(Size*sizeof(char*));
        for (i=0; i<Size; i++)
        {
            n[i] = (char*) malloc(Size*sizeof(char));
        }
        new_gen(m, Size, n);
        print_m(n, Size);
        cpy_m(n, m, Size);

    }
    return 0;   }


void print_m(char** b, int s)
{
    int i, j;
    putchar('\n');
    for (i=0; i<s; i++)
    {
        for (j=0; j<s; j++)    {
            printf("%c", *(*(b+i)+j));
        }
        putchar('\n');
    }
    return;
}


void cpy_m(char* b[MSIZE],char** a, int s)
{
    int i, j;
    for (i=0; i<s; i++) {
        for (j=0; j<s; j++) {
            *(*(a+i)+j) = b[i][j];
        }
    return;
}}

最佳答案

考虑这对嵌套循环

for (i=1; i<gen; i++)
{
    char **n = (char**) malloc(Size*sizeof(char*));
    for (i=0; i<Size; i++)
    {
        n[i] = (char*) malloc(Size*sizeof(char));
    }
    new_gen(m, Size, n);
    print_m(n, Size);
    cpy_m(n, m, Size);
}

第一点,两个循环都使用i作为控制变量,但它们是嵌套的。

第二点,您在每次迭代中覆盖来自 malloc 的指针(没有 free)。

关于c - 在c中重新填充二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34681540/

相关文章:

c++ - 指向特征矩阵的指针数组

C - 从 uint8_t 函数返回失败

c - printf() 与 scanf() 在同一行

c - 使用指针从另一个编译单元访问和更改静态变量

c - 指针初始化无法识别定义的类型

C编程: array not have any bound

c - 使用 rpmlib 将标签添加到 header

c# - 从 C# 调用 C# : How to marshall that one 2D array of doubles when the others go so well?

Javascript 数组在控制台中显示 2 个值,访问时仅显示 1 个

java - 缩放表示像素的字节数组的函数