PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, August 16, 2022

[FIXED] How to access the members of structure through pointers same as we access array?

 August 16, 2022     c, character, output, pointers, structure     No comments   

Issue

I got a Question in a mock test which is not running in IDE but I could not understand the concept behind that piece of code given in test.

printf (“%c, %c”, *( (char*) q + 1) , *( (char*) q + 2) ) ; Here how an pointer to struct q can access the members of pointers using numbers.

Here is the link for the code

https://ide.geeksforgeeks.org/7V6mVJZvre


Solution

In c, struct members just memory space mapped to that struct definition. A struct with three chars means 3 byte space mapped to the this struct.

q is a pointer. So q + 1 means one address forward to the base struct address

(char*) means this is not a struct anymore this is a char pointer

*( (char*) q + 2) ) or simply *x means dereference the pointer so get the char value.

There are some exceptions (if not all members are the same type) check Structure padding and packing



Answered By - Furkan
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing