困惑 : Pointers and character arrays in C

标签 c pointers strtok character-arrays

我是 C 的新手,正在尝试拆分字符数组(我从 Ardunio 的串行端口接收到)。我查阅了一些教程并想出了这个。请帮我调试一下。

char action[10];
unsigned long duration;

void split(char input[20])
{
 char *param, *ptr;

 param = strtok_r(input, "#", &ptr);
 action = *param;                      // Need help with this line

 param = strtok_r(NULL, "!", &ptr);
 duration = (unsigned long) *param;    // Need help with this line
}

据我了解,strtok_r 返回指向分隔符 (#) 之后的字符的指针。那么,如果我想让 action[] 成为 input[] 的子集字符数组,直到分隔符,我应该怎么做?

编辑: 输入是这样的:“left#1000!”

最佳答案

看起来您的第一个标记是字符串,第二个标记是长整数。您可以使用 strncpyparam复制到action中,然后strtoulunsigned long 解析为 duration

param = strtok_r(input, "#!", &ptr);
strncpy(action, param, sizeof(action));
// Force zero termination
action[sizeof(action)-1] = '\0';

param = strtok_r(NULL, "#!", ptr);
duration = strtoul(param, &param, 10);

关于困惑 : Pointers and character arrays in C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11505165/

相关文章:

c - 在 C 中打开 mp 需要更长的时间来处理 black_scholes 算法

c - 使用结构时取消引用 'void *' 指针

c - 将字符串指针数组传递给函数并读取字符串的值

c - C : *source++, (*source)++, *(source)++ 中的差异

c - strtok 和 strcpy 错误

c++ - 以 24 小时格式表示的两次时间之间耗时 hh :mm:ss

C - strtok 和 strcmp

从用户空间调用驱动程序 API 的成本

c - 将文件的行读取到链接列表中

c++ - 试图删除指针触发断点