Seems like I still didn’t get the pointers in C right.
I want the length of the global array (pointer) j being dynamic.
I have this (Arduino) code
unsigned int* j;
void setup() {
Serial.begin(9600);
initj();
Serial.println(j[0]); //111 -> right
Serial.println(j[0]); //768 -> wrong!
Serial.println(j[1]); //32771 -> wrong!
}
void initj() {
unsigned int i[2];
i[0] = 111;
i[1] = 222;
j = i;
Serial.println(j[0]); // 111 -> right
Serial.println(j[1]); // 222 -> right
}
void loop() {
}
How can I do this right?
Thank you in advance!
Your
initj()function setsjto point at a local array. The lifetime of this array is limited to the function call itself, as soon as the function returns, the pointer is no longer valid. Attempting to dereferencejis therefore undefined behaviour.I don’t know exactly what you want to do, but three possibilities are:
iat global scope instead.iasstatic.malloc(maybe unsuitable for an embedded platform).