hello i m doing some function for saving a structure of some employee to text but i want to do it using ptrs to struct normally i tried first using ptr to struct in some main function to test some stuff abt it but i get runtime error

#include <stdio.h>
struct employee {
    char SzName[100];
    int age;
    int payee;
};
int main(void)
{
    struct employee *em1;
    em1->age=12;
    printf("%d\n",em1->age);
    getchar();
    return 0;
}

why do i get this runtime error ? its like doign *x=12 but with structures or do i get runtime error coz the ptr to struct isnt intilised ?but its alrdy intilised since struct employee *em1 should point to its aaddress or whats wrong ?

Recommended Answers

All 5 Replies

Whenever you use pointers make sure that you allocate memory first before using them.

i know but isnt this alrdy have the address of the structure ?

or i have to declare normal structure of same type and make the ptr get its address ?

yah solved it but thats weird if they intilise it using
struct employee *em1; they should have did just struct *ptr; then ptr=&em1; lol

or i have to declare normal structure of same type and make the ptr get its address ?

You can do it that way, or allocate memory to your structure pointer as in:

em1 = malloc( sizeof(*em1) );
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.