繁体   English   中英

有人可以解释为什么我的程序崩溃吗?

[英]Can someone please explain why my program crashes?

我在编译时没有任何错误。 该程序只是在我运行时崩溃。 我尝试直接从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);
}

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

两件事情:

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

其次,当您仅将指针传递到某个数据结构(例如4x5整数数组)时,编译器将无法得出此数据结构的布局。 即,像a[i][j]这样的语句将要求编译器“知道”每行i由4列j ,这样它就可以计算应将值存储到的“位置”,即a + (4*i) + j 编译器根本不知道每行的列数nr,即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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM