Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer arithmetic for structs

Given a struct definition that contains one double and three int variables (4 variables in all), if p is a pointer to this struct with a value 0x1000, what value does p++ have?

This is not a homework problem, so don't worry. I'm just trying to prepare for a test and I can't figure out this practice problem. Thanks

This is in C. Yes I want the value of p after it is incremented. This is a 32-bit machine

like image 965
user950891 Avatar asked Oct 01 '11 23:10

user950891


People also ask

Can we have a pointer to a struct?

As we know Pointer is a variable that stores the address of another variable of data types like int or float. Similarly, we can have a Pointer to Structures, In which the pointer variable point to the address of the user-defined data types i.e. Structures.

How do you increment a pointer structure?

When a pointer is incremented, it actually increments by the number equal to the size of the data type for which it is a pointer. For Example: If an integer pointer that stores address 1000 is incremented, then it will increment by 2(size of an int) and the new address it will points to 1002.

Can we do pointer arithmetic?

We can perform arithmetic operations on the pointers like addition, subtraction, etc. However, as we know that pointer contains the address, the result of an arithmetic operation performed on the pointer will also be a pointer if the other operand is of type integer.

What is the size of a pointer to a struct?

Pointers are always the same size on a system no matter what they're pointing to (int, char, struct, etc..); in your case the pointer size is 4 bytes.


1 Answers

struct foobar *p;
p = 0x1000; 
p++;

is the same as

struct foobar *p;
p = 0x1000 + sizeof(struct foobar);
like image 117
tangrs Avatar answered Oct 08 '22 21:10

tangrs