【问题标题】:how to pass a struct of array to function如何将数组结构传递给函数
【发布时间】:2018-05-21 15:28:46
【问题描述】:

我有这段代码,我想把它变成一个函数,我不知道怎么做,这段代码从文件中读取作者,并将它们放在一个数组中。我注意到主文件变得太大,所以我必须精简它。 nartisti 是文件中实际包含的艺术家数量。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#define max 30            
#define maxu 20            
#define sessomu 6          
#define sessom 6          

struct cantanti
{
int id;
char nome[max],cognome[max],nazionalita[max],sesso[sessom],genere[max];
};
struct cantanti arrayc[100];

 case 1:
    {
        system("cls");//pulisco lo schermo

        FILE *fp;//puntatore a file
        int nartisti;//variabile per contare quanti artisti ci sono nel file
        fp=fopen("artisti.dat","r");//apro il file artisti in modalita' lettura
        fscanf(fp,"%d",&nartisti);//leggo da file il numero degli artisti presenti
        int i=0;//azzero la variabile per ciclare il contatore
        printf("  _____________________________________________________________________________________\n");
        printf("|| %-5s || %-12s || %-12s || %-15s || %-4s || %-12s ||\n","<ID>","<NOME>","<COGNOME>","<NAZIONALITA'>","<SESSO>","<GENERE>");
        printf("||_______||______________||______________||_________________||_________||______________||\n");

        while(i!=nartisti)
        {
            //scansioni gli artisti da file, gli inserisco in un array di cantanti e li visualizzo a schermo
            fscanf(fp,"%d %s %s %s %s %s",&arrayc[i].id,arrayc[i].nome,arrayc[i].cognome,arrayc[i].nazionalita,arrayc[i].sesso,arrayc[i].genere);
            printf("||%-6d || %-12s || %-12s || %-15s || %-7s || %-12s ||\n",arrayc[i].id,arrayc[i].nome,arrayc[i].cognome,arrayc[i].nazionalita,arrayc[i].sesso,arrayc[i].genere);
            printf("||_______||______________||______________||_________________||_________||______________||\n");
            i++ ;
        }
        //mi dice quanti cantanti sono stati letti
        printf("**************************|    Sono stati letti %d autori dal file      |****************\n",nartisti);
        printf("***************************\\___________________________________________/ ****************\n\n");
        fclose(fp);//chiudo il file

        system("pause");
        system("cls");//pulisce lo schermo
    }
    break;

【问题讨论】:

  • 你的代码中的函数在哪里?
  • 我希望你帮我写它,据我了解我应该只传递数组和文件,但我不能这样做
  • 首先你应该决定你想要在函数中使用什么代码,因为你已经开始使用 case 语句并且代码也打印出数组 - 如果它是一个用于读取的函数,它应该只是这样做。

标签: c arrays structure


【解决方案1】:

你首先需要声明函数

void readAuthors()

或者返回数组

struct readAuthors()

然后像往常一样写函数

void/struct readAuthors(){ 
    <code>
}

之后就可以调用函数了

readAuthors()
or
array = readAuthors

希望对你有帮助

【讨论】:

  • 你不能在 C 中返回一个数组。
  • void readAuthors() - 我应该在 main 之前写 void/struct readAuthors(){ } 在 main 之后 - struct readAuthors() 在 main 之后?
  • struct readAuthors() 缺少结构的名称,只会返回其中一个
猜你喜欢
  • 2015-02-24
  • 1970-01-01
  • 2011-04-06
  • 1970-01-01
  • 1970-01-01
  • 2015-12-23
  • 1970-01-01
相关资源
最近更新 更多