Chinaunix
标题:
putchar 对引用的会有字符串有影响??
[打印本页]
作者:
萎代码
时间:
2009-02-26 14:59
标题:
putchar 对引用的会有字符串有影响??
下面的代码 屏蔽putchar和不屏蔽putchar 打印的结果是不同的,putchar会对引用的字符串有影响??
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
typedef struct {
int Id;
int DevId;
char Name[32];
char Desc[64];
}DevStateDesc;
DevStateDesc data[4] = { {1,11,"name11","desc11"},
{2,22,"name22","desc22"},
{2,22,"name222","desc222"},
{3,33,"name33","desc33"} };
#ifndef WIN32
DevStateDesc *getData(char* format,...)
#else
DevStateDesc *getData(char* format,va_alist)
va_dcl
#endif
{
va_list list;
char *tmp = NULL;
int arg_len = 0;
int i=0;
char *string = strdup(format);
char *sep = "%";
char *token = NULL;
#ifndef WIN32
va_start(list,format);
#else
va_start(list);
#endif
//test the first wheather is NULL
if (va_arg(list,char*) == NULL )
{
goto END_CODE;
}
else
{
va_end(list);
//start again
#ifndef WIN32
va_start(list,format);
#else
va_start(list);
#endif
}
//token by %
token = strtok(string,sep);
while( token != NULL)
{
//printf("%s\n",token);
char c = *token;
//putchar(c);
{
switch(*token)
{
case 'd':
printf("%s is int type %d\n",++token,va_arg(list,int));
break;
case 's':
printf("%s is char pointer %s\n",++token,va_arg(list,char*));
break;
default :
printf("default");
break;
}
}
token = strtok(NULL,sep);
}
END_CODE:
va_end(list);
free(string);
return NULL;
}
int main(int argc, char *argv[])
{
getData("%dId%sName",2,"name22",NULL);
return 1;
}
复制代码
屏蔽的打印结果是
Id is int type 2
Name is char pointer name22
不屏蔽的打印结果是
dId is int type 2
sName is char pointer name22
先谢谢各位大侠先
作者:
zhuhefang2006
时间:
2009-02-26 23:40
什么叫屏蔽putchar啊,怎么看不懂啊
作者:
萎代码
时间:
2009-02-27 08:16
哦,不规范,我这里 屏蔽 的意思是 注释。
你方便试试这些代码在你的机器 是否有类似的现象吗?
作者:
Roemer
时间:
2009-02-27 08:28
你启用putchar自然要多打印一些东西了。putchar也要输出~
作者:
萎代码
时间:
2009-02-27 10:02
对对,写代码写晕了,呵呵,太感谢楼上的
想实现像printf一样可以格式化的取结构里面的数据的。
不知你有什么好建议好思路呢?
欢迎光临 Chinaunix (http://bbs.chinaunix.net/)
Powered by Discuz! X3.2