Тому що ви повертаєте значення char
, що означає тільки перший символ рядка, вказаний вказівником p
. вашої функції.
Ваша функція повинна мати прототип:
char* ParseCmd(char *buf,int len);
^^^^^
Online Demo:
#include
#include
#include
char* ParseCmd(char *buf,int len)
{
char *p;
p = strtok(buf," ");
char *ptr = (char *)malloc(strlen(p)+1);
strncpy(ptr,p,strlen(p));
return ptr;
}
int main()
{
char array[]="fsa rew qwe";
char* ret = ParseCmd(array,11);
printf("[%s]",ret);
/*If You Forget this,You cause a Memory Leak*/
free(ret);
return 0;
}
Output:
[fsa]
Disclaimer: I have not really used any C++
in the code because since You are using strtok
and char *
instead of string
I believe the Q is more C
than C++
.