You can't call strtok()
on a string literal, because string literals are constant. Generally it's safer to declare pointers to string literals with the const
qualifier, to ensure the compiler will warn you when the program tries to modify the pointee.
You need to make your string an array instead of a pointer to a string literal, like this
static char __rx_data[] = "AT+CGMI\r";
this is an array of 9
bytes containing a string of 8
characters which you can modify, strtok()
does modify it's arguments.
You also need to allocate space for your struct
to be able to use it, you can do it in two ways, using malloc()
AT_msg_Data *data;
data = malloc(sizeof(*data));
if (data == NULL)
return -1; /* failed to allocate memory -- exit the program */
or, just create an instance on the stack
AT_msg_Data data;
/* ^ no star here */
and then access it's members with a .
instead of ->
.
Another way which does not apply in this case because your string cannot be allocated dynamically, is to use malloc()
or strdup()
.
You could also use strchr()
like this
const char *plus;
plus = strchr(__rx_data, '+');
if (plus != NULL)
{
size_t length; /* maybe use `ptrdiff_t' here but just for illustration */
length = plus - __rx_data;
data->header = malloc(length + 1);
if (data->header != NULL)
{
memcpy(data->header, __rx_data, length);
data->header[length] = '\0';
data->body = strdup(plus + 1);
}
/* note: data->header can be `NULL' from here, so check that before using it */
/* this also applies to data->body */
}
This way you will not need to modify __rx_data
which is better because it's a global variable and I assume you are going to reuse it. You should make your code safer by then redeclaring
static const char *const __rx_data = "AT+CGMI\r";
if you are going to use the strchr()
approach.
With this declaration __rx_data
cannot be reassigned or modified without the compiler complaining about it.
Your code will anyway fail later, because the '\0'
placed by strtok()
at the position of the +
sign will be overwritten with the +
once you call strtok()
again, strtok()
keeps an internal buffer to restore the replaced characters that also makes it unsafe if your program is multithreaded.