Link to home
Start Free TrialLog in
Avatar of g_temp
g_temp

asked on

Array of Structure

Hello,

Does anyone know how to create array of struct
and pass into a function and how to access it
in the functin ?
Avatar of djbusychild
djbusychild

#include <stdio.h>

typedef struct mystruct {
     int i;
} mystruct_st;


void func(mystruct_st* user_struct, int len)
{
     int i;
     for (i = 0;i<len;i++) {
          printf("struct %d = %d\n",i,user_struct[i].i);
     }
}

int main(int argc, char* argv[])
{
     int i;
     mystruct_st struct_arr[5];
     
     for (i = 0;i<5;i++) {
          struct_arr[i].i = i;
     }

     func(struct_arr,5);

     return 0;
}
Avatar of g_temp

ASKER

What if i want a dynamic char instead of int ?
same thing

just use char* instead of int
and malloc character array

#include <stdio.h>

typedef struct mystruct {
    char* i;
} mystruct_st;


void func(mystruct_st* user_struct, int len)
{
    int i;
    for (i = 0;i<len;i++) {
         printf("struct %d = %d\n",i,user_struct[i].i);
    }
}

int main(int argc, char* argv[])
{
    int i;
    mystruct_st struct_arr[5];
   
    for (i = 0;i<5;i++) {
         struct_arr[i].i = (*char)malloc(256);
    }

    func(struct_arr,5);

    return 0;
}
ASKER CERTIFIED SOLUTION
Avatar of djbusychild
djbusychild

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I think you forgot this question. I will ask Community Support to close it unless you finalize it within 7 days. Unless there is objection or further activity,  I will suggest to accept "djbusychild" comment(s) as an answer.

If you think your question was not answered at all, you can post a request in Community support (please include this link) to refund your points.
The link to the Community Support area is: https://www.experts-exchange.com/jsp/qList.jsp?ta=commspt

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!
======
Werner

Accepted question as recommended.

Regards,
ComTech
CS @ EE