0

I am trying to hack the general C rules while research and try to store memory address in variable but my code failed with Segmentation fault (core dumped) when running under 64-bit system. And I know why - because of 4/8-bits (32/64-bit systems) of memory. The question is: what primitive type (not uintptr_t) I need to satisfy both systems? long long int? My source:

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

unsigned int hacky_nonpointer;

hacky_nonpointer = (unsigned int) char_array;

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

}

storenth
  • 101
  • Are you asking how to use a single fixed-size type whose size doesn't depend on whether you're building 32-bit or 64-bit? Is that why you don't want to use uintptr_t? If so, just use uint64_t – Useless Aug 21 '20 at 16:11
  • the posted code does not compile! It is missing the statement: #include <stdio.h> – user3629249 Aug 21 '20 at 20:10

1 Answers1

2

Use the appropriate pointer type:

#include <stdio.h>

int main() { int i;

char char_array[5] = {'a', 'b', 'c', 'd', 'e'};
char *char_pointer = char_array;

for(i=0; i &lt; 5; i++) {
    printf(&quot;[char_pointer] points to %p, which contains the char '%c'\n&quot;,
       char_pointer, *char_pointer);
    char_pointer++;
}

}

Stephen Kitt
  • 434,908