如何正确管理strtok_r的输出?

问题描述 投票:0回答:1

假设我有一个char缓冲区,其数据用char“:”;]分隔。

char pt[256] = "pt:ct:mac";
char *plain_text;
char *cipher_text;
char *mac;

char *next = NULL;
char *tokens = NULL;
const char sep[2] = ":";    

tokens = strtok_r(pt, sep, &next);

do
{
    if(i == 0)
    {
        int ln = strlen(tokens);
        plain_text = (char*)malloc(ln * 1);
        i++;
        continue;
    }
    if(i == 1)
    {
        int ln = strlen(tokens);
        cipher_text = (char*)malloc(ln * 1);
        i++;
        continue;
    }
    if(i == 2)
    {
        int ln = strlen(tokens);
        mac = (char*)malloc(ln * 1);
        i++;
        continue;
    }
 }
 while((tokens = strtok_r(NULL, sep, &next)) != NULL);

 free(plain_text);
 free(cipher_text);
 free(mac);

,所以问题是如何以正确的方式处理strtok_r输出结果。

基本上,主要目的是从pt字符串中获取结果,并将其放入动态容器中。因为,我不知道plain_text和cipher_text的大小。

这是编程的正确方法吗?

除此之外,如果看到一些小错误或可以采用更好的做法写一些东西,请让我知道;)谢谢!

假设我有一个char缓冲区,其数据用char“:”分隔; char pt [256] =“ pt:ct:mac”;字符* plain_text;字符* cipher_text; char * mac; char * next = NULL; char *令牌= NULL; const char ...

c strtok
1个回答
0
投票

我会用指针数组来做。

© www.soinside.com 2019 - 2024. All rights reserved.