如何将数组从函数返回到main [英] How to return an array from function to main
问题描述
我必须使用该函数来打开文件,读取文件,将第一个值保存为以下元素(尺寸)的数量以及seq[]
数组中的其他值.
我不知道如何在主目录中同时返回维度和seq[]
.我需要它,因为我必须在其他函数中使用这些值.如代码所示,该函数返回维(dim),但我不知道如何返回数组.
I have to use the function to open a file, read it, save the first value as the number of following elements (dimension) and the other values in the seq[]
array.
I don't know how to return both dimension and seq[]
in the main; I need it because I have to use these values in other functions. As the code shows, the function returns the dimension (dim), but I don't know how to return the array.
#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
;我必须返回两个值(维度和数组).而且,我无法编辑该函数的参数.
I think the focus of the problem is *seq
; I have to return two values (dimension and array). Moreover, I can't edit the parameters of the function.
我认为我的问题不同于这,因为在我的函数中有一个带有指针的参数,而函数没有指针...
I think my question is different from this because in my function there is a parameter with a pointer, and the function hasn't got a pointer...
推荐答案
更改函数以按指针获取数组指针:
Change the function to take the array pointer by pointer:
int leggiSequenza(char *nomeFile, int **seq);
// ^^^^^^^^^
然后用您的变量地址调用它:
Then call it with the address of your variable:
leggiSequenza(nomeFile, &dimensione);
// ^^^^^^^^^^^
在函数定义内,更改周围的细节,如下所示:
Inside the function definition, change the details around like so:
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;
}
最后,调用者需要释放数组:
Finally, the caller needs to free the array:
free(dimensione);
更新:由于您已经提出了以下问题:在呼叫站点预分配内存:
Update: Since you've re-asked your question: Pre-allocate the memory at the call site:
int * p = malloc(200 * sizeof(int));
int dim = leggiSequenza(filename, p);
// ...
free(p);
这篇关于如何将数组从函数返回到main的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!