gpt4 book ai didi

困惑 : Pointers and character arrays in C

转载 作者:太空宇宙 更新时间:2023-11-04 06:38:46 25 4
gpt4 key购买 nike

我是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com