如何解决如何将空指针转换为C中的字符串?
我正在使用通用链接列表编写通用堆栈程序。基本上,每个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;
}
可读的输出仅是名称和等级。其他数值变量仅返回一些奇怪的符号。希望问题清楚,谢谢!
解决方法
这段代码没有什么意义:
/* Format all data to be string */
sprintf(str,"%s ",(char*)(currNd -> data)); (1)
printf("%s\n",str); (2)
因为(1)表示currNd-> data实际上是一个字符串。 如果currNd-> data是字符串,则无需将其转换为临时(已分配)字符串。
这行就足够了:
printf("%s\n",currNd -> data);
我们不能过多地讲代码,因为我们不了解push
和LinkedList
。但是我认为push
需要做2件事。如果参数是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;
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。