C 中 char 数组的动态内存分配问题

Issue with Dynamic Memory Allocation for a char Array in C

我正在尝试用 c 语言编写一个程序,为维度为 n,m 的 'char' 数组分配内存。下面是我尝试过的,但每次我 运行 它时,无论我给它什么尺寸 returns 值 -2 甚至没有打印 "Error in memory allocation."。 大家怎么看?

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

int main(void){
    int i,j,n,m;
    char **p;
    scanf("%d %d",&n,&m);         //get array dimensions
    p=malloc(n*sizeof(char *));
    if (p==NULL){
        printf("Error in memory allocation.\n");
        return -1;
    }
    for (i=0;i<n;i++){
        p[i]=malloc(m*sizeof(char));
        if (p[i]==NULL)
            printf("Error in memory allocation.\n");
            return -2;
    }
}

谢谢!

    if (p[i]==NULL)
        printf("Error in memory allocation.\n");
        return -2;

必须是

    if (p[i]==NULL) {
        printf("Error in memory allocation.\n");
        return -2;
    }

一些编码指南要求始终将 {} 与 if 语句(即使是单个语句)放在一起以避免此类问题。