我用strtok()来标记函数中的字符串.将值复制到全局char数组后,我打印这些值以确保功能.一切都很好,但当我想访问它们时,它们就被销毁了.

以下是代码:

#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;
}

this is output enter image description here

我想将值分配给 struct ,但没有分配.

推荐答案

您可以使用以下代码来解决问题:

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;
}

C++相关问答推荐

如何判断宏参数是否为C语言中的整型文字

C中是否有语法可以直接初始化一个常量文本常量数组的 struct 成员?

在列表中插入Int指针(C)

Make Node函数.S有什么问题吗?

强制转换变量以在 struct 中蚕食

在编写代码时,Clion比vscode有更多的问题指示器

如果格式字符串的内存与printf的一个参数共享,会发生什么情况?

Fprintf正在写入多个 struct 成员,并且数据过剩

OSDev--双缓冲重启系统

如何在C中用bool进行文件I/O?

如何摆脱-WIMPLICIT-Function-声明

为什么我的半数组测试和奇数组测试不起作用?(我使用Assert进行调试)

浮点正零何时不全为零?

分配给静态变量和动态变量的位置之间有区别吗?

当读取可能会阻塞管道中的父进程时,为什么要等待子进程?

C 程序不显示任何输出,但它接受 CS50 Lab1 的输入问题

一元运算符

在带中断的循环缓冲区中使用 易失性

strided memcpy(3) 在 libvpx 中如何工作

C 初学者 - struct 中的字符串不需要 Malloc