【问题标题】:Double pointer to a 1D array指向一维数组的双指针
【发布时间】:2014-09-03 04:15:23
【问题描述】:

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

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

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);

}

希望这是可读的。谢谢。

【问题讨论】:

  • 什么是image_data?它在哪里声明?为什么你认为你可以分配给一个数组?数组是不可修改的左值,不能赋值给数组。

标签: c arrays pointers malloc


【解决方案1】:

您正在结合两个不同的问题:文件 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);
}

(我们甚至可以取消 arr,但让我们慢慢来。)

一旦清楚这一点,您就可以将其拼接到处理文件 I/O 的代码中。请记住,始终孤立地开发新功能。

【讨论】:

    【解决方案2】:

    试试这个

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-18
      • 2017-06-11
      • 1970-01-01
      相关资源
      最近更新 更多