2014-09-03 169 views
-3

请耐心等待,因为我几乎不知道我在说什么。我试图从PGM文件读取数据(不包括标题)。我有一个函数(read_data),它接受一个双指针(char **数据)作为参数。指向一维数组的双指针

在函数中,我可以将数据放入一个数组(arr),但我的问题是将该指针(**数据)分配给该数组。这是我的代码到目前为止:

read_data(char* file, char** data) { 
FILE *fp = fopen(file, "rb"); 
char type[3], dump; 
int i =0, data_length; 
int w, h; // width & height 

fgets(type, sizeof(type), fp); 
fscanf(fp, "%d", &w); 
fscanf(fp, "%d", &h); 

if (strcmp(type, "P5 ")) { 
    data_length = w * h; 
    } 
else { 
    data_length = (w * h) * 3; 
    } // this is to work out the size of the array (how many bits of data are in the file) 

char arr[data_length]; 

while ((dump = fgetc(fp)) != '\n'); // just to skip the header 

for (i; i < data_length; i++) { 
arr[i] = fgetc(fp); 
} 

data = &arr; // <--- The problem 

fclose(fp); 

return data_length; 

} 

main() { 
int data_length; 
char **data = malloc(sizeof(int*)*data_length); 

read_data("file.pgm",data); 

} 

希望这是可读的。谢谢。

+1

什么是'image_data'?它在哪里宣布?你为什么认为你可以分配给一个数组?数组是不可修改的l值,您不能分配给数组。 – 2014-09-03 04:32:01

回答

-1

试试这个

int n = 0; 

while(condition) 
    nextchar = fgetc(filepointer); 
    (*image_data)[n]= nextchar; 
    // or (*data)[n]= nextchar; 
    n++; 
2

要结合两个不同的问题:文件I/O和指针处理。由于真正的问题是指针处理,我们使用一个更简单的例子。首先,可以创建和填写的char阵列功能:

#include <stdio.h> 
#include <string.h> 

void foo() 
{ 
    char arr[6]; 
    strcpy(arr, "hello"); 
    printf("%s\n", arr); 
} 

到目前为止,一切都很好。 (从这里开始,我将忽略#include指令。)但是这是一个堆栈中的数组,所以当控制超出函数时,它会变回荒野。我们要动态分配,在堆:

void foo() 
{ 
    char *arr = malloc(6*sizeof(char)); 
    strcpy(arr, "hello"); 
    printf("%s\n", arr); 
} 

注:在你的问题你声明的功能外阵列,但是这意味着你必须这样做不知道它应该是什么长度,这没有按这似乎是你想要的,这是一种更清洁的方法,如果你真的想在外面声明数组,你可以做到这一点,只需稍作更改。)

现在关于指针。这很容易分配此数组的地址(这是分配给arr值)到另一个指针:

char *p; 
p = arr; 

,但我们不希望分配该值在函数一些地方指针变量;我们想把它分配给代码的范围内的指针值,这个函数调用。要做到这一点与普通变量的方法是使用一个指针的变量:

void bar(int *k) 
{ 
    *k = 5; 
} 

... 
int n; 
bar(&n); 
... 

所以我们用这个指针变量相同:

void foo(char **p) 
{ 
    char *arr = malloc(6*sizeof(char)); 
    strcpy(arr, "hello"); 
    *p = arr; 
} 

int main() 
{ 
    char *z; 
    foo(&z); 
    printf("%s\n", z); 
} 

(我们甚至可以用做掉但是让我们慢慢来吧。)

一旦清楚了,就可以将它拼接到处理文件I/O的代码。请记住,始终独立开发新功能。

+0

+1指针指针的覆盖范围很好。 – WhozCraig 2014-09-03 04:40:22

+0

+1 this.helped.me.lots。感谢堆。 – 2014-09-03 04:41:58