【发布时间】:2013-10-03 09:17:48
【问题描述】:
我正在尝试使用 libjpeg 将图像的像素数据复制到矩阵中。指针出了点问题。请帮忙。
问题简述:我将int ***p 指针传递给读取像素数据的函数。在函数中,我可以访问元素 p[i][j][k] 并对它们执行操作,但是当我尝试在 main 中执行相同操作时,程序崩溃了。
主要功能是:
#include<stdio.h>
#include<stdlib.h>
#include<jpeglib.h>
#include"functions.h"
void main(void)
{
char * file="a.jpg";
int ***p; // to store the pixel values
int s[2]={0,0}; // to store the dimensions of the image
read_JPEG_file(file,p,s); // Function that reads the image
printf("%d",p[0][0][0]); // This makes the program crash
}
文件functions.h内容如下:
int read_JPEG_file(char * file, int ***p, int **s)
{
int i,j;
//-----------------libjpeg procedure which I got from the documentation------------
struct jpeg_decompress_struct cinfo;
struct jpeg_error_mgr jerr;
cinfo.err=jpeg_std_error(&jerr);
FILE * infile; /* source file */
JSAMPARRAY buffer; /* Output row buffer */
int row_stride;
if ((infile = fopen(filename, "rb")) == NULL)
{
fprintf(stderr, "can't open %s\n", filename);
return 0;
}
jpeg_create_decompress(&cinfo);
jpeg_stdio_src(&cinfo, infile);
jpeg_read_header(&cinfo, TRUE);
jpeg_start_decompress(&cinfo);
row_stride = cinfo.output_width * cinfo.output_components;
buffer=(*cinfo.mem->alloc_sarray)((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);
s[0]=cinfo.output_height;
s[1]=cinfo.output_width;
p=(int ***)malloc(s[0]*sizeof(int **));
for (i=0;i<s[0];i++)
{
p[i]=(int **)malloc(s[1]*sizeof(int *));
for (j=0;j<s[1];j++)
{
p[i][j]=(int *)malloc(3*sizeof(int));
}
}
while (cinfo.output_scanline < cinfo.output_height)
{
jpeg_read_scanlines(&cinfo, buffer, 1);
for ( i=0; i<cinfo.output_width; i++)
{
p[cinfo.output_scanline-1][i][0]=(int)buffer[0][0+3*i];
p[cinfo.output_scanline-1][i][1]=(int)buffer[0][1+3*i];
p[cinfo.output_scanline-1][i][2]=(int)buffer[0][2+3*i];
}
}
printf("%d",p[0][0][0]); // This works just fine
return 0;
}
我知道内存分配有问题,但我不知道是什么。我尝试了另一个测试程序并成功分配了一个长度为 500X500X500 整数的内存块,并且它可以正常工作 - 它输出随机整数而不会崩溃 - 所以内存不足不是问题。
【问题讨论】:
标签: c pointers memory-management user-defined-functions