简体   繁体   中英

passing array of pointers

I am trying to send a array of pointers to function.

each pointer is pointing to struct.

No idea how to do it please help me to understand what is the general body for it.

Thx.

#include <ansi_c.h>
#include <string.h>
#include <stdio.h>


void  sortbyname(struct worker   *p); 

void main()
{

    struct worker{
      char lastname[20],name[20];      
      int  age;int Seniority,salary,offdays [12];
    };

  int i,j;
  struct worker  employee[6],*pemp[6],*pS[6],*pN[6],*pill[6];


  for (i=0;i<6;i++)
  {
    pemp[i]=&employee[i];
    pS[i]=&employee[i];
    pN[i]=&employee[i];
    pill[i]=&employee[i];
  } 

  FILE *fp;
  fp=fopen("c:\\Users\\iliya\\Documents\\National Instruments\\CVI\\hw1-t2\\worker.txt","rt");       

  for (i=0;i<6;i++)
  {
    fscanf(fp,"%s",pemp[i]->lastname);
    fscanf(fp,"%s",pemp[i]->name); 
    fscanf(fp,"%d",&pemp[i]->age);
    fscanf(fp,"%d",&pemp[i]->Seniority);
    fscanf(fp,"%d",&pemp[i]->salary);
    for (j=0;j<12;j++)
    fscanf(fp,"%d",&pemp[i]->offdays[j]);

  } 

  sortbyname(pemp );
  //  sortbysalary();
  //  sortbydaysoff();             
  getchar();     
}`  

This is how you declare array of pointer :

<type> * <identifier_name> [size]

eg int *a[10] // It's the array of 10 integer pointers

It's similar for struct also :

eg

#define Max 10

typedef struct {

int a;
float b;

} Mystruct;

Mystruct * MystArray[Max];

You can write function as of your choice :

<return type>func(Mystruct * MystArray[Max])
{
 //body of func
}

<return type>func(Mystruct **MystArray)
{
 //body of func
}

<return type>func(Mystruct * MystArray[])
{
 //body of func
}

Any way arrays decay into pointers in function call

The following code can compile now but you need to fill in the rest of your code.
Hope this helps.

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

struct worker{
    char lastname[20],name[20];
    int  age;int Seniority,salary,offdays [12];
};


void  sortbyname(struct worker   *p[])
{
}

int main()
{

  int i,j;
  struct worker  employee[6],*pemp[6],*pS[6],*pN[6],*pill[6];


  for (i=0;i<6;i++)
  {
    // do something

    //pemp[i]=&employee[i];
    //pS[i]=&employee[i];
    //pN[i]=&employee[i];
    //pill[i]=&employee[i];
  }

  FILE *fp;
  fp=fopen("worker.txt","rt");

  if (fp==NULL) {
      printf("\nfopen failed\n");
      return -1;
  } else {
      printf("\nfile found\n");
  }

  for (i=0;i<6;i++)
  {
    // do something
  }

  sortbyname(pemp );
  //  sortbysalary();
  //  sortbydaysoff();
  getchar();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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