Go Down

Topic: What is wrong with this code? (Read 454 times) previous topic - next topic

Raptor5

int cmdNumber(char* cmd)
{
   char* cmd1;
   strcpy(cmd1, cmd);
   //Serial.println("123");
   char* ass = strsep(&cmd1, "M");
   ass = strsep(&cmd1, " ");
//   Serial.println(ass);
   int aaa = atoi(ass);
//   Serial.println(aaa);
   return aaa;
}

void loop()
{
   int v = cmdNumber("M1001 ");
   Serial.println(v, DEC);
...

I get 0 in my port monitor. If I uncomment Serial.println(aaa) everything goes fine and I get 1001. What the hell is wrong?  :0

AWOL

Code: [Select]
char* cmd1;
   strcpy(cmd1, cmd);

Dangerous.
Don't do it.
"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.

Raptor5

Even if I don't, still not working )

holmes4

  char* ass = strsep(&cmd1, "M");

If you want to return ass create it on the heap not the stack. The stack may be over written. Or just make it global.

Raptor5

Even this is not working

void loop()
{
   char* a = "M1001 2334 3434";
   char* a1 = strsep(&a, " ");
   Serial.println(a);

How do I create it on heap?

Arrch


   char* a = "M1001 2334 3434";


Stop creating pointers to nothing and assigning it a value. If you want to store a string of chars like that you need to actually set aside space to store those characters by using an array.

Raptor5

Please, supply an example of how to do this correctly. Thanks.

Arrch


Please, supply an example of how to do this correctly. Thanks.


Code: [Select]
char data[] = "This data is actually stored somewhere correctly";

or if you don't know what you needs to go into it yet:

Code: [Select]
char data[10];

Raptor5

#8
Nov 17, 2012, 07:49 pm Last Edit: Nov 17, 2012, 08:18 pm by Raptor5 Reason: 1
Ok. Now how do I pass this to strsep(char **sp, char*) ?
How do I convert char array to char** ?

Tom Carpenter

The same way you did before:

Code: [Select]
&data

'data' is just a pointer to the start of an array, and in this case the array is of type char, so 'data' a char*

As a side note, when you access an element of an array, you are essentially saying 'get the value stored at the pointer to the start of the array plus some offset'. e.g.:
data[0] is the same as *data
data[1] is the same as *(data + 1)
data[2] is the same as *(data + 2)
and so on.
~Tom~

Raptor5


The same way you did before:


Yes, but compiler stops me from doing like

strsep (&data, "M");

Tom Carpenter

You may have to type cast it:
Code: [Select]
strsep ((char**)&data, "M");

or if you don't want to type cast you could do:

Code: [Select]
char data[] = "whatever";
char* ptr = data;
strsep(&ptr,"M");
~Tom~

Raptor5


Go Up