+ 3
Accessing unions inside structs
how do i access unions inside structs , from a function other then main to which i passed the struct as a parameter
9 Respostas
+ 4
OK. This is interesting. A segmentation fault occurred because name and course within your struct is uninitialised. As a result, attempting to write to whatever address name and course is pointing to, will cause the program to throw segfault. For some reason, Code Playground does not show anything.
In order to fix this, you can change the char pointers to stack-allocated arrays instead.
typedef struct{
char name[20];
int enn;
char course[20];
int fee_status;
union {
char* aca[100];
int acn;
}ac_status;
}istu;
Reference: https://stackoverflow.com/questions/13447891/segmentation-fault-using-scanf
+ 4
Arun Sharma I'm not sure if it is possible to initialize and use an union which is within a struct, without being given an object of the union within the struct.
Your struct can be modified as:
typedef struct {
// other members
typedef union {
// union members
} ac_status;
} istu;
To make it possible to call
istu.ac_status.acn;
+ 4
Arun Sharma Sorry about the mess up. I was working with C++ instead of C. Check out a working example:
https://code.sololearn.com/cUfhS09buyV6/?ref=app
+ 3
Let's say your struct is:
struct Test {
union { int mem = 3939; } uObj;
};
and you pass it to a function in main:
Test obj;
access(obj);
The function should be able to access the union member by calling
obj.uObj.mem;
+ 1
here (the commented part)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
char * name;
int enn;
char * course;
int fee_status;
union ac_status{
char* aca[100];
int acn;
};
}istu;
void give_stu_info(istu stu){
printf(" name : %s \n erollment no : %d\n course : %s\n", stu.name, stu.enn, stu.course );
/* if(stu.fee_status == 0){
strcpy(stu.ac_status.aca, "admit_card_available");
printf(" %s", stu.ac_status.aca);
}else{
stu.ac_status.acn = 6006;
printf(" %d", stu.ac_status.acn);
}
*/
}
int main() {
istu arun={"arun_may", 12345678, "HCI", 0};
give_stu_info(arun);
return 0;
}
+ 1
Hatsy Rei
y r u writing istu(the structure tag) instead of stu
chaining dot operators worked fine with stucts inside structs idk if it works with unions inside structs
+ 1
also, typedef before union gives error
and u cannot declear values for union members inside the union
+ 1
hey Hatsy Rei
check this out
https://code.sololearn.com/cZ6776GJp4ow/?ref=app
could u please figure out whats wrong, it's not showing any errors
0
Hasty Rei
ya, not working
i'll show you
also i meant in c (tag)