简体   繁体   English

将指针传递给函数,同时返回int和地址(通过参数)

[英]Passing pointer of pointers to function, returning both an int and an address (by parameter)

I've got a function which, as is, works correctly. 我有一个可以正常工作的功能。 However the rest of the program has a limitation in that I've preset the size of the array (the space to be allocated). 但是该程序的其余部分有一个局限性,因为我已经预先设置了数组的大小(要分配的空间)。 Obviously, this is problematic should an event arise in which I need extra space for that array. 显然,如果发生需要为该数组提供额外空间的事件,这是有问题的。 So I want to add dynamic allocation of memory into my program. 所以我想在程序中添加动态内存分配。

But I'm having an issue with the whole pointer to a pointer concept, and I've utterly failed to find an online explanation that makes sense to me... I think I'll want to use malloc(iRead + 1) to get an array of the right size, but I'm not sure what that should be assigned to... *array? 但是我在使用整个指针指向指针概念时遇到了问题,而且我完全没有找到对我有意义的在线解释...我想我想使用malloc(iRead + 1)来得到一个合适大小的数组,但是我不确定应该将其分配给... * array? **array? **阵列? I'm not at all sure. 我完全不确定。

And I'm also not clear on my while loops. 而且我的while循环也不清楚。 &array[iRead] will no longer work, and I'm not sure how to get a hold of the elements in the array when there's a pointer to a pointer involved. &array [iRead]将不再起作用,而且当涉及到指向指针的指针时,我不确定如何获取数组中的元素。

Can anyone point (heh pointer pun) me in the right direction? 谁能朝正确的方向指点我?

I can think of the following approaches. 我可以想到以下方法。

  1. First approach 第一种方法

    1. Make two passes through the file. 通过文件两次。
    2. In the first pass, read the numbers and discard them but keep counting the number of items. 在第一遍中,读取数字并丢弃它们,但继续计数项目数。
    3. Allocate memory once for all the items. 为所有项目分配一次内存。
    4. Rewind the file and make a second pass through it. 倒带文件,然后第二遍。 In the second pass, read and store the numbers. 在第二遍中,读取并存储数字。

       int getNumberOfItems(FILE* fp, int hexi) { int numItems = 0; int number; char const* format = (hexi == 0) ? "%X" : "%d"; while (fscanf(fp, format, &number) > 0) { ++numItems; return numItems; } void read(int *array, FILE* fp, int numItems, int hexi) { int i = 0; char const* format = (hexi == 0) ? "%X" : "%d"; for ( i = 0; i < numItems; ++i ) fscanf(fp, format, &array[i]); } int main(int argc, char** argv) { int hexi = 0; FILE* fp = fopen(argv[1], "r"); // if ( fp == NULL ) // Add error checking code // Get the number of items in the file. int numItems = getNumberOfItems(fp, hexi); // Allocate memory for the items. int* array = malloc(sizeof(int)*numItems); // Rewind the file before reading the data frewind(fp); // Read the data. read(array, fp, numItems, hexi); // Use the data // ... // ... // Dealloate memory free(array); } 
  2. Second approach. 第二种方法。

    1. Keep reading numbers from the file. 继续从文件中读取数字。
    2. Every time you read a number, use realloc to allocate space the additional item. 每次读取数字时,请使用realloc为其他项目分配空间。
    3. Store the in the reallocated memory. 将储存在重新分配的内存中。

       int read(int **array, char* fpin, int hexi) { int number; int iRead = 0; // Local variable for ease of use. int* arr = NULL; char const* format = (hexi == 0) ? "%X" : "%d"; FILE *fp = fopen(fpin, "r"); if (NULL == fp){ printf("File open error!\\n"); exit(-1); } while (fscanf(fp, format, &number) > 0) { arr = realloc(arr, sizeof(int)*(iRead+1)); arr[iRead] = number; iRead += 1; } fclose(fp); // Return the array in the output argument. *array = arr; return iRead; } int main(int argc, char** argv) { int hexi = 0; int* array = NULL; // Read the data. int numItems = read(&array, argv[1], hexi); // Use the data // ... // ... // Dealloate memory free(array); } 

I'd suggest something like this: 我建议这样的事情:

int read(int **array_pp, char* fpin, int hexi) {
  ...
  int *array = malloc (sizeof (int) * n);
  for (int i=0; i < n; i++)
    fscanf(fp, "%X",&array[i]);
  ...
  *array_pp = array;
  return n;
}

Notes: 笔记:

1) You must use "**" if you want to return a pointer in a function argument 1)如果要在函数参数中返回指针,则必须使用“ **”

2) If you prefer, however, you can declare two pointer variables (array_pp and array) to simplify your code. 2)但是,如果愿意,可以声明两个指针变量(array_pp和array)以简化代码。

int read(int **array, char* fpin, int hexi) {
   int iRead = 0;
   int i, *ary;
   char *para;
   FILE *fp;

   fp = fopen(fpin, "r");
   if (NULL == fp){
      printf("File open error!\n");
      exit(-1);
   }

   para = (hexi == 0) ? "%*X" : "%*d";
   while (fscanf(fp, para)!= EOF)
     ++iRead;

   ary = *array = malloc(iRead*sizeof(int));
   if(ary == NULL){
      printf("malloc error!\n");
      exit(-2);
   }
   rewind(fp);
   para = (hexi == 0) ? "%X" : "%d";
   for(i = 0; i < iRead; ++i)
      fscanf(fp, para, &ary[i]);

   fclose(fp);
   return iRead;
}

I think you wouldn't call it an array. 我认为您不会将其称为数组。 Arrays are of fixed size and lie on the stack. 数组大小固定,位于堆栈上。 What you need (as you already said), is dynamically allocated memory on the heap. 您所需要的(如您已经说过的)是在堆上动态分配的内存。

maybe that's why you didn't find much :) here are some tutorials: 也许这就是为什么您找不到很多的原因:)这里有一些教程:

you got the function declaration correctly: 您正确获得了函数声明:

int read(int **array, char* fpin, int hexi)

What you need to do: 你需要做什么:

  1. find out how much memory you need, eg. 找出您需要多少内存,例如。 how many elements 多少元素
  2. allocate it with *array = malloc(numElements * sizeof(int)) (read "at the address pointed by array allocate memory for numElements ints") *array = malloc(numElements * sizeof(int))分配它(读取“在array指向的地址处为numElements ints分配内存”)
  3. now you can (*array)[idx] = some int (read "at the address pointed by array, take the element with index idx and assign some int to it") 现在您可以(*array)[idx] = some int (读“在array指向的地址处,使用索引为idx的元素并为其分配一些int”)
  4. call it with int* destination; int size = read(&destination, "asdf", hexi) int* destination; int size = read(&destination, "asdf", hexi)调用它int* destination; int size = read(&destination, "asdf", hexi) int* destination; int size = read(&destination, "asdf", hexi)

hope it helps.. 希望能帮助到你..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM