Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
12 years, 5 months ago.
char error on compiling
Hi all,
I have no c++ experience, so i'm stuck with a simple test program that gets the following error:
"a value of type "const char [4]" cannot be used to initialize an entity of type "char [3]"" in file "/main.cpp", Line: 5, Col: 16
The Code:
- include "mbed.h"
Serial pc(USBTX, USBRX); tx, rx
char slaveid[3]="ABC";
int main() { pc.printf("Slave id %s",slaveid);
while(1) { char c = pc.getc(); if(c == 'u'){ pc.printf("C pressed"); } if(c == 'd'){ pc.printf("D pressed"); }
} }
1 Answer
12 years, 5 months ago.
Hi,
Maybe you could use this:
line 4 new
char* slaveid = "ABC";
instead of your code:
line 4 old
char slaveid[3]="ABC";
That should work. :)
Jonas
Thanks Jonas ...
Is there some mbed c++ programming tutorials/documentation available ?
posted by 18 May 2013For documentation I generally use: http://www.cplusplus.com/
What is most often used is:
char slaveid[] = "ABC";
The problem is a bit shown here: http://www.cplusplus.com/doc/tutorial/ntcs/. Slaveid is basicly a pointer that points to where the first letter of your string is stored. The next letter is stored in the byte after that, etc. However if you pass slaveid to a function, when that function reads your string it needs to know when it has reached the last symbol of your string. That's why at the end of every string like this a NULL terminator is placed, which tells any function reading slaveid that it reached the end of slaveid.
And that is why your "ABC" has a length of 4 (3+null terminator), and you tried to fit it in slaveid which is only length 3.
posted by 18 May 2013