0
const char reset = '3';
char savedArray[32] = "0000000000000000000000000000000";
savedArray[reset] = '1';
Serial.println(savedArray[reset]);
Serial.println(savedArray[3]);
Serial.println(savedArray);

So I am changing the value of the savedArray at position 3, but when I read it out again I find it 0.. What am I doing wrong? Why isn't reset the same as 3?

Serial output:

1
0
0000000000000000000000000000000
6
  • 1
    use saveArray[32] = {0}; instead of savedArray[32] = 0000000000000000000000000000000"; Commented Sep 19, 2016 at 7:54
  • 4
    '3' is ASCII and is 48 + 3. Commented Sep 19, 2016 at 7:55
  • 1
    Why are you using char reset and not int reset ? Commented Sep 19, 2016 at 7:55
  • @MathewsMathai It should be size_t reset, if we wanted to nitpick. Commented Sep 19, 2016 at 8:10
  • 1
    @MathewsMathai No, it was me nitpicking :) char and int will work (because 3 fits), size_t would be the choice for generic indexing. Commented Sep 19, 2016 at 8:38

3 Answers 3

4

Assuming ASCII or even EBCDIC encoding '3' is a value larger than 32. (In ASCII, it's 51).

The behaviour on using this in savedArray[reset] is undefined since you are attempting to access an index outside the bounds of the array savedArray. Use const char reset = 3; to assign the numeric value of 3 to any numeric type, including const char.

Sign up to request clarification or add additional context in comments.

Comments

3

No, you are changing the array element 51 (the value of '3' in the ASCII table), so you are accessing outside of the bounds of the array.

Change to const char reset = 3;

Comments

2

So I am changing the value of the savedArray at position 3.

Wait, there you went wrong. You're not at all changing the value at position 3. In your code,

const char reset = '3';

is the same as

const char reset = 51;  //considering ASCII

because, character literal (constant)'3' represents decimal 51 (in ACSII) and for which , later

savedArray[reset] = '1';

is out of bound access, as savedArray is of size 32. You might want to write

 const char reset = 3;  //decimal 3

or,

#define RESET 3  //MACROS are better suited as "array index", just suggesting

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.