- 2072 Kartik · 2 marks
Effect of Ptr++ on pointer
Short answer
Ptr++ increments by sizeof(the pointed-to type) bytes. For char*: 1 byte, int*: typically 4 bytes, double*: 8 bytes, and for a struct pointer: size of the struct including padding (e.g., 16 bytes in the example).
If Ptr is a pointer to user defined type or basic type, by how many bytes is Ptr incremented when the statement Ptr++ is executed?
Ptr++ increases the pointer by sizeof(the type it points to) bytes, so that it points to the next element of that type. The compiler scales the increment automatically.
char *: 1 byteint *: 4 bytes (typical)double *: 8 bytes- pointer to a structure:
sizeof(struct), including any padding
#include <stdio.h>
struct rec { char name[10]; int roll; };
int main(void)
{
char c[2]; int i[2]; double d[2]; struct rec r[2];
char *pc = c; int *pi = i; double *pd = d; struct rec *pr = r;
printf("char : %ld byte(s)\n", (long)((char *)(pc + 1) - (char *)pc));
printf("int : %ld byte(s)\n", (long)((char *)(pi + 1) - (char *)pi));
printf("double : %ld byte(s)\n", (long)((char *)(pd + 1) - (char *)pd));
printf("struct : %ld byte(s)\n", (long)((char *)(pr + 1) - (char *)pr));
return 0;
}
Output (typical 64-bit system):
char : 1 byte(s)
int : 4 byte(s)
double : 8 byte(s)
struct : 16 byte(s)
The structure takes 16 bytes: 10 for name, 2 bytes of padding so that roll starts at a multiple of 4, and 4 for roll.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Switch versus user defined function · Computer Programming, chapter 5
- Significance of user defined functions · Computer Programming, chapter 6
- Copy string converting lower to upper using pointer · Computer Programming, chapter 9 · asked 3×
- Nested if with flowchart · Computer Programming, chapter 5
- Conditional operator vs if-else; digit sum · Computer Programming, chapter 5
- Convert user-defined type to basic type · Object Oriented Programming, chapter 5
- Muster roll for user's committee project · Construction Management, chapter 8
- Why n-type has many conduction electrons · Electrical Engineering Material, chapter 6
- How many times more acidic: pH 6.5 and 7.8 · Water Supply Engineering, chapter 4