CodexBloom - Programming Q&A Platform

Invalid conversion when using struct pointers in C - Pointer arithmetic guide

šŸ‘€ Views: 0 šŸ’¬ Answers: 1 šŸ“… Created: 2025-06-14
c pointers structs segmentation-fault C

I'm stuck trying to I'm working on a personal project and I'm working with an scenario related to pointer arithmetic when working with structs in C. I have a struct defined as follows: ```c typedef struct { int id; char name[50]; } Person; ``` I created an array of `Person` and I'm trying to iterate through it using pointers. Here's the code where the question occurs: ```c #include <stdio.h> #include <string.h> int main() { Person people[3]; for (int i = 0; i < 3; i++) { people[i].id = i + 1; snprintf(people[i].name, sizeof(people[i].name), "Person %d", i + 1); } Person *ptr = people; for (int i = 0; i < 3; i++) { printf("ID: %d, Name: %s\n", (ptr + i)->id, (ptr + i)->name); } return 0; } ``` The code compiles fine, but when I run it, I get the following output: ``` ID: 1, Name: Person 1 ID: 2, Name: Person 2 ID: 3, Name: Person 3 ``` This part works correctly, but I then tried to do something similar using a pointer that was cast to a `void *` type for generic processing, like this: ```c void printPeople(void *data, size_t count) { Person *ptr = (Person *)data; for (size_t i = 0; i < count; i++) { printf("ID: %d, Name: %s\n", (ptr + i)->id, (ptr + i)->name); } } int main() { // ... (initialization code) printPeople((void *)people, 3); } ``` However, when I call `printPeople`, it appears to be reading memory incorrectly, leading to a segmentation fault when trying to access `name`. I suspect this might be an scenario with how I'm passing the pointer or incorrect assumptions about the memory layout of the struct. I've also confirmed that the `count` parameter is correctly indicating 3 entries. Any ideas on what might be going wrong here? I’m using GCC 11.2 on Ubuntu 20.04 and I’m compiling with `-Wall -Wextra` flags but getting no warnings. I'd appreciate any insights or solutions! I'm working on a application that needs to handle this. How would you solve this? I'm working with C in a Docker container on CentOS. Any help would be greatly appreciated!