Maker Pro
Maker Pro

What happens inside if statement in code

champ1

Jul 17, 2018
55
Joined
Jul 17, 2018
Messages
55
I am stuck in c structure program. I don't have idea What happens inside if statement in code

Code:
#include<stdio.h>
#include<stdlib.h>

struct s
{
    int x;
    int y;
};

int main ()
{
    struct s *p = NULL;
   
    p = malloc(sizeof(*p));
   
    if ( p != NULL )
    {
        printf("%d\n", p-> x);
        p = p -> y;
    }
   
    free (p );
   
    return 0;
   
}
I guess p is structure pointer point to memory location of structure member x.
Code:
printf("%d\n", p-> x);

My confusion is whether the pointer is dereferenced or not ?
 

Harald Kapp

Moderator
Moderator
Nov 17, 2011
12,715
Joined
Nov 17, 2011
Messages
12,715
Where did you get that code from?
If it is from a website, you could ask there.
If it is your code, you should know what you do.

Anyway, I doubt the person who wrote this code knew how to deal with pointers in C.
Code:
printf("%d\n", p-> x);
Makes no sense: After
Code:
p = malloc(sizeof(*p));
you have reserved memory (allocated memory) for a structure "s", but you haven't initialized the values for x and y. Unless your compiler does that for you (and I wouldn't rely on this), the contents of the memory locations is undefined and the print statement will result in a more or less arbitrary number.

The next statement
Code:
p = p -> y;
also makes no sense to me. "p" is a pointer to a "struct s" element, whereas p -> y is an integer. While some compilers may create code for this, chances are your pointer now points into nirvana.
Try this code (only the relevant snippet shown here):
Code:
    p = malloc(sizeof(*p));
    p->x = 27; //  I initialize x and y with defined values
    p->y = 33;
  
    if ( p != NULL )
    {
        printf("%d\n", p-> x); // prints 27 on the console
        p = p -> y;
        printf("%d\n", p-> y); // prints nothing on my console - may be different on your computer
    }
    }
When you instead try this:
Code:
    p = malloc(sizeof(*p));
    p->x = 27;
    p->y = 33;
   
    if ( p != NULL )
    {
        printf("%d\n", p-> x);
        printf("%d\n", p-> y);
    }
You'll see actually 27 and 33 printed on the console.
 
Top