1,105,286 Community Members

Structure Pointer

Member Avatar
ram619
Junior Poster
100 posts since Mar 2010
Reputation Points: 8 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

This code is crashing, please tell me for what all I need to assign memory.

Thanks

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

struct s1
{
    char *p1;
};

struct s2
{
    struct s1 *p2;
};

struct s3
{
    struct s2 *p3;
}*p4=NULL;

int main()
{
    char a='a';

    p4=malloc(sizeof(struct s3));

    p4->p3->p2->p1=&a;

    printf("%c",*(p4->p3->p2->p1));

    return 0;
}
Member Avatar
deceptikon
Eternally Awesome
4,662 posts since Jan 2012
Reputation Points: 1,339 [?]
Q&As Helped to Solve: 678 [?]
Skill Endorsements: 104 [?]
Administrator
Featured
 
1
 

You only allocated memory for p4. p3, p2, and p1 are all still uninitialized.

Member Avatar
ram619
Junior Poster
100 posts since Mar 2010
Reputation Points: 8 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
1
 

Thread Solved. Posting code here so that it may help someone else.

:)

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


struct s1
{
    char *p1;
};

struct s2
{
    struct s1 *p2;
};

struct s3
{
    struct s2 *p3;
}*p4;


int main()
{
    char a='z';

    p4=malloc(sizeof(struct s3));

    p4->p3=malloc(sizeof(struct s2));

    p4->p3->p2=malloc(sizeof(struct s1));

    p4->p3->p2->p1=&a;

    printf(" %c \n",*(p4->p3->p2->p1));


    return 0;
}
Question Answered as of 1 Year Ago by deceptikon
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: