Good day everyone,
I've got a rather simple C newbie question. Working with CPCtelera, so SDCC is the compiler. What's the difference between these two programs:
#include <stdio.h>
#include <types.h>
const u8 lvl1[3] = {1, 2, 3};
const u8 lvl2[2] = {4, 5};
u8* jagged[2];
int main() {
jagged[0] = lvl1;
jagged[1] = lvl2;
for (int i = 0; i < 2; i++) {
printf("%x\n", *jagged[i]);
}
}
Outputs "1 4", as expected. If I print the pointer (jagged{i}) instead of the value, I get the correct memory adresses of lvl1 and lvl2 respectively.
However the following doesn't work:#include <stdio.h>
#include <types.h>
const u8 lvl1[3] = {1, 2, 3};
const u8 lvl2[2] = {4, 5};
u8* jagged[2] = {lvl1, lvl2};
int main() {
for (int i = 0; i < 2; i++) {
printf("%x\n", *jagged[i]);
}
while(1);
}
This outputs "1 1". If I print the pointer, it's just 0 for both arrays.
What's going wrong here?
Thanks for any help.
Cheers
Nothing is wrong in your C code, but cpctelera/SDCC don't initialize not constant global variable, because they take double space in memory.
Here the detailed explanation :
https://www.cpcwiki.eu/forum/programming/cpctelerasdcc-initialization-of-variables-and-arrays-in-headerfile/msg112905/#msg112905
Thanks for the quick response Arnaud, that clears up some things for me. It works now.
But what's the difference between u8* const arr[] and const u8* arr[]? I had already tried the latter, obviously.
Cheers
Quote from: Norman on 13:15, 01 August 20u8* const arr[]
is a pointer to an array of constants.
Quote from: Norman on 13:15, 01 August 20 const u8* arr[]
Is a constant pointer to an array.
the last is a C related question, there are a lot of answers online.
this is what I remember: (quote from one of the online answers)
Read it backwards...
int* - pointer to int
int const * - pointer to const int
int * const - const pointer to int
int const * const - const pointer to const int
---
so:
u8* const arr[]
should be ARRAY of const pointers to u8
const u8* arr[]
should be ARRAY of pointers to const u8
but please double check...
I would advice to check your main binary .map file for l__INITIALIZED, and its size MUST be 0 or you'll need initialised data and cpctelera apparently has removed that from the CRT0.
I do that too :)