【问题标题】:How to typecast a void pointer into a string in C?如何将 void 指针类型转换为 C 中的字符串?
【发布时间】:2021-01-13 21:04:59
【问题描述】:

我正在使用通用链表为通用堆栈编写程序。基本上,每个 currNd -> data 都是 void* 数据。所以我使用 sprintf 将数据实际格式化为我的 str 字符串变量。但问题是当 currNd 是整数或实数时,它不起作用。是否有任何建议将 double、float、int 转换为字符串变量,以便我可以在我的 toString 函数中使用它?

这是插入代码

char *name = "Alex";
int id = 23219434;
int age = 24;
double mark = 89.5;
char grade = 'A';

push( stack, name );
push( stack, &id );
push( stack, &age );
push( stack, &mark );
push( stack, &grade );

printf("%s\n", toString(stack)); /* Output is only Alex (some strange symbols) and A */

我的 toString

char* toString(LinkedList *list)
{
    char *str = (char*) malloc(sizeof(char) * STR_LENGTH);

    /* Traversal starts from head */
    LinkedListNode *currNd = list -> head;     

    /* Store the string as traversing the linked list */
    while( currNd != NULL )
    {
        /* Format all data to be string */
        sprintf(str, "%s ", (char*)(currNd -> data));
        printf("%s\n", str);
        currNd = currNd -> next; /* Move to the next node */
    }
    return str;
}

可读的输出只有姓名和等级。其他数值变量只是返回一些奇怪的符号。希望问题清楚,谢谢!

【问题讨论】:

  • 发布minimal reproducible example,就像您的问题几乎无法回答一样。你是说类型转换吗?
  • 是的,我已经更正了
  • 23219434 对于int 来说可能太大了,int 需要能够保持至少32768 的值。如果要存储最多 32 位的整数,请使用 longuint_least32_tuint_fast32_tuint32_t,它们可能存在也可能不存在。

标签: c generics linked-list stack void-pointers


【解决方案1】:

这段代码没有多大意义:

/* Format all data to be string */
sprintf(str, "%s ", (char*)(currNd -> data)); (1)
printf("%s\n", str);                          (2)

因为 (1) 表示 currNd->data 实际上是一个字符串。 如果 currNd->data 是字符串,则不需要将其转换为临时(malloced)字符串。

这一行就足够了:

printf("%s\n", currNd -> data);

关于代码我们不能说太多,因为我们不知道pushLinkedList。但我认为push 需要做两件不同的事情。如果参数是string,则应将其存储为string。如果参数是integer,则应将其存储为integer

因此,函数push 似乎缺少枚举类型参数。

push( stack, name, TT_TYPE_STRING ); // will store the string
push( stack, id,  TT_TYPE_INT  );    // will store the integer
push( stack, age, TT_TYPE_INT  );    // will store the integer

关于函数toString() 它应该检查项目的类型。如果是字符串,前面的printf("%s", ...)应该没问题,如果是整数,应该调用printf(%d", ...)

所以我希望你的数据结构会漏掉一个重要的点:

struct ListItem
{
  enum ItemType; /* INT OR String OR Something */
  int IntValue;
  char *StringValue;
};

【讨论】:

  • 我明白了,我错过了枚举。谢谢
猜你喜欢
  • 2021-09-20
  • 2019-05-09
  • 1970-01-01
  • 1970-01-01
  • 2017-10-07
  • 1970-01-01
  • 1970-01-01
  • 2023-02-26
相关资源
最近更新 更多