could be a c question

Mar 10, 2018 at 3:28pm
http://cs-fundamentals.com/c-programming/memory-layout-of-c-program-code-data-segments.php

I'm reading the above article on how a C program is represented in memory I am guessing that it is the same for a c++ program

anyway one part of the code has me confused and this may just be something that is common in C

why do we have to cast the memory address of int x to a char pointer?

char *c = (char*) &x;

why don't we just do

char* c = &x;?

thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21


#include <stdio.h>
 
int main ()
{
  unsigned int x = 0x76543210;
  char *c = (char*) &x; // part of code I'm confused with 
 
  if (*c == 0x10)
  {
    printf ("Underlying architecture is little endian. \n");
  }
  else
  {
     printf ("Underlying architecture is big endian. \n");
  }
 
  return 0;
}


Mar 10, 2018 at 4:38pm
Did you try without the cast?

An online (C++) compiler spits out:
 In function 'int main()':
8:14: error: cannot convert 'unsigned int*' to 'char*' in initialization


In other words the compiler has a (documented) set of implict conversion rules, but they fail to solve the char *c = &x;.
Mar 10, 2018 at 5:56pm
oh ok so you are basically telling the compiler to cast then store the memory address of x in a char pointer instead of an int pointer?

so in this basic program why did we need to convert it to a char pointer,why couldn't we just have checked the int in the if conditions?

thanks
Topic archived. No new replies allowed.