c - 如何从函数返回数组到main

标签 c arrays pointers

我必须使用该函数打开一个文件,读取它,将第一个值保存为以下元素(维度)的数量,并将其他值保存在 seq[] 中。大批。 我不知道如何同时返回维度和 seq[]主要;我需要它是因为我必须在其他函数中使用这些值。正如代码所示,该函数返回维度(dim),但我不知道如何返回数组。

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

int leggiSequenza(char *nomeFile, int *seq) {

FILE *in;
int i;
int dim;

if((in = fopen(nomeFile, "r"))==NULL) {
    printf("Error.\n");
    return -1;
}

fscanf(in, "%d", &(dim));
printf("Find %d values.\n", dim);

if(dim < 0) {
    printf("Errore: negative value.\n");
    return -1;
}

seq = (int*) malloc(dim*sizeof(int));

i=0;
while(!feof(in) && i<(dim)) {
    fscanf(in, "%d", &seq[i]);
    i++;
}

for(i=0; i<(dim); i++) {
    printf("Value in position number %d: %d.\n", i+1, seq[i]);
}

free(seq);
fclose(in);

return dim;
}


int main(int argc, char* argv[]) {

int letturaFile;
char nomeFile[200];
int *dimensione;

printf("Insert file name:\n");
scanf("%s", nomeFile);
printf("\n");
letturaFile = leggiSequenza(nomeFile, dimensione);
dimensione = &letturaFile;
printf("dimension = %d\n", *dimensione);

return 0;
}

我认为问题的焦点是*seq ;我必须返回两个值(维度和数组)。而且,我无法编辑该函数的参数。

我认为我的问题与 this 不同因为在我的函数中有一个带有指针的参数,而该函数没有指针......

最佳答案

更改函数以通过指针获取数组指针:

int leggiSequenza(char *nomeFile, int **seq);
//                                ^^^^^^^^^

然后用变量的地址调用它:

leggiSequenza(nomeFile, &dimensione);
//                      ^^^^^^^^^^^

在函数定义内,更改详细信息,如下所示:

int leggiSequenza(char *nomeFile, int **seq) {
  // ...
  int *local_seq = malloc(dim*sizeof(int));

  // use local_seq in place of seq

  // free(local_seq);   // delete ...
  *seq = localsec;      // ... and replace with this

  return dim;
}

最后,调用者需要释放数组:

free(dimensione);

<小时/>

更新:由于您重新提出了问题:在调用站点预先分配内存:

int * p = malloc(200 * sizeof(int));

int dim = leggiSequenza(filename, p);

// ...

free(p);

关于c - 如何从函数返回数组到main,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41840003/

相关文章:

c - C 中数组索引自动赋值?

arrays - 在 O(n) 中查找总和为零的子数组的数量

javascript - 如何提取嵌套对象数组的值?

c - 迭代器效率: pointer compare or counter

c++ - 为什么我不能在初始化列表中使用箭头运算符?

c - 为什么将浮点值转换为 int 时值会发生变化

c - 如何创建正确的 Makefile 以及依赖项的顺序重要吗?

c - 将包含字符串的结构写入二进制文件

javascript - 将特定的 JS 对象值附加到它被单击的 div

变量地址的C地址