Egemen Sarımaden Egemen Sarımaden - 1 month ago 9
C Question

Creating a pointer in C

I use Ubuntu 14.10 and GCC. I am trying to create a pointer with unsigned integer type but I get this message:

Segmentation fault (core dumped)


This is my code. I used gdb and think that the error has to do with my
printf
statements:

#include <stdio.h>

int main() {
int i;
char char_array[5] = {'a', 'b', 'c', 'd', 'e'};
int int_array[5] = {1, 2, 3, 4, 5};

unsigned int hacky_nonpointer;
hacky_nonpointer = (unsigned int) char_array;

for (i = 0; i < 5; i++) {
printf("[hacky_nonpointer] points to 0x%08x which contains the char '%c' \n",
hacky_nonpointer, *(char *(hacky_nonpointer)));
hacky_nonpointer = hacky_nonpointer + sizeof(char);
}

hacky_nonpointer = (unsigned) int_array;

for (i = 0; i < 5; i++) {
printf("[char pointer] points to %08x, which contains the integer %d\n",
hacky_nonpointer, *((int *)hacky_nonpointer));
hacky_nonpointer = hacky_nonpointer + sizeof(int);
}

return 0;
}

Answer

unsigned int may not be large enough to hold a pointer. You should use uintptr_t from stdint.h if available (size_t if not).