Kiran C K
Kiran C K

Reputation: 63

Passing address of structure to a function

I have declared a structure inside main(). I want to pass the structure's address to a function. It shows structure is not declared error. I know that if a structure is declared inside main() its scope is limited. But here, I am passing the address to the function. Still it shows an error that bank * unknown size. What should I do to pass the structure's address declared inside main? Here is my code:

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

void edit_data(struct bank *acc_data)

{
    int loop;
    for(loop=0;loop<200;loop++) 
    {
       *(acc_data+loop).acc_no = 1000+loop;
        (acc_data+loop).name = "a1";
        (acc_data+loop)->balance = 1000;
    }
};

int main()
{
    int loop;

    struct bank
    {

        long acc_no;

        char name[80];

        int balance;

    }data[200];

    edit_data(data);
}

Upvotes: 2

Views: 2073

Answers (1)

tomsoft
tomsoft

Reputation: 4577

You are mixing the declaration of the variable, and the declaration of the type of the variable. Your function should know the type, and this type is currently declared in the main part of the program. To solve it, declare the type in the global space:

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

struct bank
{
    long acc_no;
    char name[80];
    int balance;
};

void edit_data(struct bank *acc_data)
{
  int loop;
  for(loop=0;loop<200;loop++)
  {
      (acc_data+loop)->acc_no = 1000+loop;
      strcpy( &(acc_data+loop)->name , "a1");
      (acc_data+loop)->balance = 1000;
  }
};
int main()
{
   int loop;
   struct bank data[200];
   edit_data(data);
}

Please note that you had also some pointer error in your edit data function....

It's also usually better to use array instead of pointer in that case:

void edit_data(struct bank *acc_data)
{
  int loop;
  for(loop=0;loop<200;loop++)
  {
      acc_data[loop].acc_no = 1000+loop;
      strcpy( acc_data[loop].name , "a1");
      acc_data[loop].balance = 1000;
  }
};

Upvotes: 4

Related Questions