c - 帕斯卡三角形和动态内存分配问题,c

标签 c memory dynamic allocation realloc

我正在为我的 C 编程类(class)编写代码,并偶然发现了一个问题。我应该编写一个程序,它将显示为输出帕斯卡三角形。我将使用一维数组,并在每次迭代中使用 realloc 使数组更大。问题在于,即使当我在第七列中键入“7”(作为三角形的高度)时,代码会编译并运行,但也会出现垃圾号码。我不知道为什么会这样。我是动态内存分配的初学者,所以请温柔一点。

这是我的代码:

int i,n;
printf("Give the height:\n");
scanf("%d", &n);
int *tab = (int*)malloc(sizeof(int));
int *tab2, liczba=2;
for(i=0;i<n;i++)
{
    tab2=(int *)realloc(tab,i+1);
    tab2[i]=&liczba;
    print(tab2, i+1);
    printf("\n");
}

void print(int *tab, int size)
{
    int i;
    for(i=0;i<size;i++) printf("%d\t", tab[i]);
}

最佳答案

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

void print(int *tab, int size);

int main(void){
    int i, j, n;
    printf("Give the height:\n");
    scanf("%d", &n);
    int *tab = NULL;

    for(i=1;i<=n;++i){
        int *temp = realloc(tab, i * sizeof(*tab));
        if(temp)
            tab = temp;
        else {
            perror("realloc");
            free(tab);
            exit(EXIT_FAILURE);
        }
        tab[i-1] = (i == 1) ? 1 : 0;
        for(j=i-1;j>0;--j){
            tab[j] += tab[j-1];
        }
        print(tab, i);
    }
    free(tab);
    return 0;
}

void print(int *tab, int size){
    int i;
    for(i=0;i<size;i++){
        if(i)
            putchar('\t');
        printf("%d", tab[i]);
    }
    putchar('\n');
}

关于c - 帕斯卡三角形和动态内存分配问题,c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31077501/

相关文章:

c - 异常抛出 : read access violation

windows - Windows 中的内存是如何组织的?

c - 探索结构包装

php - 下拉菜单和 where 语句

android - 如何在即时应用中包含即时动态功能模块?

python-3.x - 在 python 中即时编译字符串函数?

c - 对限制限定符的详细但可读的解释?

使用有符号字符指针更改 int 数组的值

有人可以帮我解决算法中的错误吗

python - 从脚本运行 scrapy 时内存溢出