I use strtok()
to tokenize my string in a function. After copying the values to a global char
array, I print the values to ensure the functionality. Everything is OK, but when I want to access them they are destroyed.
this is the code:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
int client, count = 0;
volatile char *token_temp[30];
volatile int toknum = 0;
int text_test()
{
char my_tokenised_string_buffer[255] = "Response\n\nCompany\nModel\nRevision: N01234567890\n\nOK";
const char delimiters[3] = "\n";
char *token = strtok(my_tokenised_string_buffer, delimiters);
token_temp[0]= token;
printf("first tokenised value = %s\n", token);
while (token != NULL) {
++toknum;
token = strtok(NULL, delimiters);
token_temp[toknum]= token;
printf("toknum : %d\t", toknum);
printf("token id from inside tokenise loop : %s -> [%u]\n", token_temp[toknum], toknum);
}
printf("\n\n\n");
for (int i = 0; i < toknum; i++) {
printf("token [%d] value in function out of tokenise = %s\n", i, token_temp[i]);
}
return 0;
}
int main()
{
text_test();
printf("\n\n\n");
for (int i = 0; i < toknum; i++) {
printf("token [%d] value in main = %s\n", i, (char *)token_temp[i]);
}
return 0;
}
I want to assign the values to structures but they are missed.
You can use this code for solve your problem :
enter code here
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
//------------------------------------------------------------
int SpliteMessage(char* input , char sp , char token_temp[10][40])
{
int len = strlen(input);
int i,token_cnt=0,bcnt=0;
for (i=0 ; i<len ; i++)
{
if (input[i] == sp)
{
token_temp[token_cnt][bcnt] = 0;
token_cnt++;
bcnt=0;
}
else
{
token_temp[token_cnt][bcnt] = input[i];
bcnt++;
}
}
return token_cnt;
}
//----------------------------------------------------------------
int main()
{
char buffer[200] = "Response\n\nCompany\nModel\nRevision: N01234567890\n\nOK";
char t_temp[10][40];
int token_counter = SpliteMessage(buffer , '\n' , t_temp);
printf("\n--------------\n(Token Counter -> %i)\n",token_counter);
for (int i=0 ; i<token_counter ; i++)
printf("token[%i] from main: (%s) \n",i,t_temp[i]);
return 0;
}