Go Down

Topic: Help with reading string from serial (Read 3 times) previous topic - next topic

AWOL

'Better' is a tricky concept.
Given a processor with large amounts of memory and a well written String class, String objects would be much simpler for most people to use.
We don't have the luxury of large amounts of memory on the AVR, so Strings can be problematical.
IMHO, it is better to get used to C strings and their methods.

But that's just my opinion.
"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.

Nick Gammon


Also by adding '\0' to the char[] and then casting, will it make it a legit String?


No. That simply makes a valid null-terminated C string. You might be able to pass that to a String class constructor however.

Quote
I need the string methods for later on.


Can you demonstrate how exactly?

Quote
I don't quite understand why everyone says char arrays are better than Strings.


Let's say you stick with Strings (not C strings). Then we can pretty confidently predict that in a week or two you will make a post along the lines of "my program hangs after it has been running for a few days". This may not necessarily be due to an underlying bug in the system, but due to memory fragmentation.

Nate711

How can I return a char array in a method? For example:
Code: [Select]

loop() {
   char[50] foo;
   foo = aMethod();
}

char[] aMethod() {
   char[50] rar = {'a','b','c','d'};
   return rar;
}

GoForSmoke

string.h for C strings, as opposed to String.h for C++ strings, has a nice set of string-manipulation routines.

http://www.nongnu.org/avr-libc/user-manual/group__avr__string.html

All a C string is is a byte array with a 0 (byte=0, not character '0') on the end. Only 1 byte overhead.
It's very simple and direct, easy to manipulate with or without a set of special functions. Very hands-on.

I find it harder to express logic in English than in Code.
Sometimes an example says more than many times as many words.

PaulS

Quote
How can I return a char array in a method? For example:

You can't. In that example, rar is a local variable, allocated on the heap. When the function ends, the heap can be overwritten at any time. Having a pointer to that memory is not a useful thing to have. It is what you would have, though, if you returned rar from the function.

What you need to do is pass a pointer to an array to the function, and have the function populate the pointed to array.

Code: [Select]
void aMethod(char *arrayToPopulate)
{
  arrayToPopulate[0] = 'a';
  arrayToPopulate[1] = 'b';
  arrayToPopulate[2] = 'c';
  arrayToPopulate[3] = 'd';
}


Then call it:
Code: [Select]
   char[50] foo;
   aMethod(foo);

Go Up