1

I have code that looks like this:

char* talk[516] = {(char*)1};
#define testValue (*(int*)talk[0]) 

I receive a null pointer exception when the following line of code is then called.

testValue = 0; 

Why is that? Haven't all value of the talk[] been initialised?

EDIT

What I want to do is, there are 516 number values (floats and ints) which are stored in char* array. testValue should point to the int value that is stored in the first element of the array. The next value along might be #define testValue2(*(float*)talk[1]).

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Shani de Leeuw
  • 171
  • 1
  • 11

3 Answers3

2

For char* talk[516] = {0};, all the elements (i.e char*) of talk are initialized with value 0 (i.e. null pointer).

For char* talk[516] = {(char*)1};, the 1st element of talk is initialized with value 1, which is not a valid value for pointer. (And the other elements are still initialized as null pointer.) *(int*)talk[0] fails, because you're trying convert a char* to int*, which points to memory address 1, and then dereference on it.

You should initialize elements with valid value, such as:

int i;
float f;
void* talk[516] = {&i, &f, /*...*/};

#define testValue (*(int*)talk[0]) 
#define testValue2 (*(float*)talk[1]) 

testValue = 1; 
testValue2 = 1.5; 

1. Note if use new to initialize elements of talk, you need to delete them at last.
2. You could use loop to initialize talk too.
3. Using char* instead of void* is confusing, IMO.
4. Consider about using std::map instead of macro magic.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
0
char* talk[516] = {0};

This means that the elements of the array talk are all NULL pointers. So when you try to deference it you get that exception.

nishantsingh
  • 4,537
  • 5
  • 25
  • 51
0

See the following substitution sequence

testValue = 0;
#
(*(int*)talk[0]) = 0;
#
char* c = talk[0]; // == 1
(*(int*)c) = 0;
#
char* c = talk[0];
int* i = (int*)c; // == ? (*)
(*i) = 0;

* Alignment issues on pointer casting

Casting a char* to int* results in undefined behavior, since int* has stricter alignment requirements than char*.

Community
  • 1
  • 1
grek40
  • 13,113
  • 1
  • 24
  • 50