struct name
        int a;
        char b[10];
        char c;
int main()
        struct name *p;
        char *n;
        n = (char *)malloc(3 * sizeof(char)); // in this why 3 means.. its my condition
        n = (char *)p;
        n->a = 3; // this line is showing error why?

/////// This is my outline of my program .......Doubt is wheter we can assign character pointer to structure pointer.......if its true means why the last line is showing error can anyone solve this fully upto n[3] and print..............other condition is we have to give value for structure not by user.......

Edited by __avd: Added [code] tags. For easy readability, always wrap programming code within posts in [code] (code blocks).

6 Years
Discussion Span
Last Post by Banfa

OK you CAN assign a structure pointer to a char point but it is not a terribly good idea and doesn't serve any good purpose on the whole.

On your malloc line you assign a value to n, it points at some allocated data.

Then on the next line you assign to n the value of p. Firstly this is a memory leak, you have just lost the pointer to the allocated memory and no-longer have any means to free it. Secondly p is not initialised to anything and strictly speaking using an uninitialised automatic scope variable is undefined behaviour.

Then you try n->a . N is a char pointer, it has no members, *n is a char. You could use p->a but p does not have a valid value yet.

I don't know what you are trying to achieve but I suspect you want something more like

struct name* p;
p = malloc(sizeof *p);
p->a = 3;

/* More code here */

/* Now I have finished with p */

No need for any char pointer.

Edited by Banfa: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.