1

I'm working in C on an arduino project and I have the following situation:

I have 3 char arrays of different sizes, and I'd like to store the address of each of these in a fourth array.

I need these to be the address of each of the char arrays because I'd like to modify data_a, data_b, and data_c, later in the code, and have the all_data array still point to the modified arrays.

unsigned char data_a[8] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07};
unsigned char data_b[3] = {0x08, 0x09, 0x0a};
unsigned char data_c[7] = {0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11};

int all_data_array_length = 3;

unsigned char* all_data[all_data_array_length] = {&data_a, &data_b, &data_c};

...

/*modify the data_a, data_b, data_c arrays */

...

for(int i = 0; i<all_data_array_length; i++) {
    /* do something with what all_data[i] points to /*
}

This leads to:

cannot convert 'unsigned char (*)[8]' to 'unsigned char*'

I think where I am confused is the distinction between char* and char[], and how to create a pointer to a char array.

All help is appreciated!

3 Answers3

0

Replace:

unsigned char* all_data[all_data_array_length] = {&data_a, &data_b, &data_c};

with:

unsigned char* all_data[3] = {&data_a[0], &data_b[0], &data_c[0]};
Arvindsinc2
  • 716
  • 7
  • 18
0

This line:

unsigned char* all_data[all_data_array_length] = {&data_a, &data_b, &data_c};

needs to be:

unsigned char* all_data[all_data_array_length] = {data_a, data_b, data_c};

or

unsigned char* all_data[all_data_array_length] = {&data_a[0], &data_b[0], &data_c[0]};

(Notice the &'s are removed).

data_a is of type unsigned char[8] (similarly data_b and data_c). &data_a is thus a pointer to an array of 8 unsigned chars: unsigned char (*)[8]. This is because an array gets converted into a pointer to its first element in most contexts in C.

See What is array decaying? and When is an array name or a function name 'converted' into a pointer ? (in C)

So when you try to assign them an array of unsigned char*'s the types don't match.

P.P
  • 117,907
  • 20
  • 175
  • 238
0

char* is a pointer to a character or character array, whereas char[] is an array. For Example. char* temp = "abc" ; here, 'temp' is a character pointer and points to the memory location of first character of the string , that is 'a' . char temp[] = "abc" ; here, 'temp' is a character array and holds the value of all the contents, i.e "abc" . Coming to your code,

unsigned char* all_data[all_data_array_length] = {&data_a, &data_b, &data_c}; 

To create a pointer to a character array, all you need to do is pass the array name, which basically is also a pointer pointing to the 1st element of the array. So change your code to

unsigned char* all_data[all_data_array_length] = {data_a, data_b, data_c};

This should work. Good luck.