段故障,在c中分配给双指针 [英] segment fault, assigning to double pointer in c

查看:72
本文介绍了段故障,在c中分配给双指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于如何为双指针正确分配内存,我有些困惑.

I am getting a little confused as to how to properly allocate memory for double pointers.

我的代码第二次尝试在第一个UCHAR指针数组的第二个索引处存储值时导致段错误.

My code causes a segment fault the second time it attempts to store a value at the 2nd index of the first UCHAR pointer array.

任何帮助将不胜感激.

分配我的双指针:

        width = BMP_GetWidth (bmp);
        height = BMP_GetHeight (bmp);
        depth = BMP_GetDepth (bmp);

        r = (UCHAR **) malloc(sizeof(UCHAR *) * height);
        g = (UCHAR **) malloc(sizeof(UCHAR *) * height);
        b = (UCHAR **) malloc(sizeof(UCHAR *) * height);

        init_rgb(bmp, width, height, r, g, b);

试图利用指针(x = 1失败):

attempting to utilize the pointer (fails on x = 1):

void init_rgb(BMP *bmp, UINT w, UINT h, UCHAR **r, UCHAR **g, UCHAR **b) {
        printf("%ld, %ld\n", w, h);
        UINT x, y;
        for (y = 0; y < h; y++) {
            r[y] = (UCHAR *)malloc(sizeof(UCHAR) * w);
            for (x = 0; x < w; x++) {
                BMP_GetPixelRGB(bmp, x, y, &r[y][x], &g[y][x], &b[y][x]);
                printf("FAILING After First Iteration\n");
            }
        }
    }

推荐答案

看起来您需要像这样的行

Looks like you need a line like

r[y] = (UCHAR *)malloc(sizeof(UCHAR) * w);

用于 g b .如果你不这样做,g[y]b[y] 是未定义的.当您引用这些代码时,您的代码可能会失败.

for g and b as well. If you don't do that, g[y] and b[y] are undefined. Your code is probably failing when you reference those.

这篇关于段故障,在c中分配给双指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆