【发布时间】: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 位的整数,请使用long、uint_least32_t、uint_fast32_t或uint32_t,它们可能存在也可能不存在。
标签: c generics linked-list stack void-pointers