【问题标题】:Can someone please explain why my program crashes?有人可以解释为什么我的程序崩溃了吗?
【发布时间】:2017-01-29 20:38:07
【问题描述】:

我在编译时没有收到任何错误。当我运行它时,程序就会崩溃。我尝试直接从 generate 函数打印矩阵,它打印了第一行和第二行。

这是我的代码

void generate(int **a)//*Function to generate a matrix a[i][j]=i+j*
{
    int i,j;
    for(i=0;i<5;i++){
        for(j=0;j<4;j++){
            a[i][j]=i+j;
        }
    }
}

void print(int **a)//*print the resulting matrix from generate function*
{
    int i,j;
    for(i=0;i<5;i++){
        for(j=0;j<4;j++){
            printf("%d ",a[i][j]);
        }
        printf("\n");
    }
}

int main()
{
    int *a=(int*)malloc(5*4*sizeof(int));//*allocating memory for a matrix of 4 lines and 5 columns.*
    generate(&a);
    print(&a);
}

【问题讨论】:

  • 您的函数不知道有哪些行和列。他们不会仅仅因为您希望他们收到 2 星指针。检查编译器警告。
  • 指向指针 (&amp;a) 的指针与二维数组不同。

标签: c pointers memory crash malloc


【解决方案1】:

1) 您正在分配单维内存。

a[i][j]=i+j; //is not valid.

下面是修改后的代码

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

void generate(int *a)//*Function to generate a matrix a[i][j]=i+j*
{
    int i,j;
    for(i=0;i<5;i++){
        for(j=0;j<4;j++){
            *a=i+j;
                a++; //increments to next memory location
        }
    }
}

void print(int *a)//*print the resulting matrix from generate function*
{
    int i,j;
    for(i=0;i<5;i++){
        for(j=0;j<4;j++){
            printf("%d ",*(a++)); //notice another way of accessing 
        }
        printf("\n");
    }
}

int main()
{
    int *a=(int*)malloc(5*4*sizeof(int));//*allocating memory for a matrix of 4 lines and 5 columns.*
    generate(a);
    print(a); //passing the pointer
    free(a); //Always always practice to free the allocated memory, don't ever do this mistake again
    return 0;
}

【讨论】:

  • 非常感谢
  • @Mamaliga 欢迎:)
【解决方案2】:

两件事:

首先,int ** 表示指向指向 int 的指针的指针,而不是指向 int 数组的指针。

其次,当你只是传递一个指向某个数据结构的指针时,例如一个 4x5 整数数组,则编译器无法导出此数据结构的布局。 IE。像a[i][j] 这样的语句将要求编译器“知道”每一行i 由4 列j 组成,这样它就可以计算应该存储值的“位置”,即a + (4*i) + j。编译器根本不知道每行的列数,即4

要克服这个问题,同时保持数组的大小至少是潜在可变的(注意“4”和“5”仍然在函数中硬编码),您可以执行以下操作:

void generate(int *a)//*Function to generate a matrix a[i][j]=i+j*
{
    int i,j;
    for(i=0;i<5;i++){
        for(j=0;j<4;j++){
            *(a+(i*4+j)) = i+j;
        }
    }
}

void print(int *a)//*print the resulting matrix from generate function*
{
    int i,j;
    for(i=0;i<5;i++){
        for(j=0;j<4;j++){
            printf("%d ", *(a+(i*4+j)));
        }
        printf("\n");
    }
}

int main()
{
    int *a=(int*)malloc(5*4*sizeof(int));//*allocating memory for a matrix of 4 lines and 5 columns.*
    generate(a);
    print(a);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-26
    相关资源
    最近更新 更多