关于char buf[128]的初始化问题

LAST_MAN 2012-05-31 05:14:23
char buf[128];
char a[10]="1233445";
strcat(buf,a);
printf("%s",buf);
打印出来的是乱码?为什么?是因为buf没有初始化吗?

char buf[128];
FILE *fp = fopen("a.txt", "r");
while(NULL != fgets(buf, 128, fp))
printf("%s", buf);
fclose(fp);

这样buf没有初始化,却可以正常运行,为什么呢?

...全文
574 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
giant7 2012-05-31
  • 打赏
  • 举报
回复
{0}
#include <stdio.h>
#include <stdlib.h>

#define MAXSIZE 100

main()
{
FILE *fp;
if ( (fp = fopen( "c:\\a.txt", "r" )) == NULL ) printf("ERROR!\n");
int tmp[MAXSIZE];
int i;
for ( i=0; i<MAXSIZE; i++ )
{
tmp[i] = 0;
}
char chtmp[10000];
i=0;
while ( !feof(fp) && i!=MAXSIZE )
{
fscanf( fp, "%d ", &tmp[i] );
//printf("tmp[%d]=%d",i,tmp[i]);
i++;
}
for ( i=0; i<MAXSIZE; i++ )
{
printf( "tmp[%3d]=%d\n", i, tmp[i] );
}
fclose( fp );
system("PAUSE");
}

giant7 2012-05-31
  • 打赏
  • 举报
回复
#include <stdio.h>
#include <stdlib.h>

#define MAXSIZE 100

main()
{
FILE *fp;
if ( (fp = fopen( "c:\\a.txt", "r" )) == NULL ) printf("ERROR!\n");
int tmp[MAXSIZE];
int i;
for ( i=0; i<MAXSIZE; i++ )
{
tmp[i] = 0;
}
char chtmp[10000];
i=0;
while ( !feof(fp) && i!=MAXSIZE )
{
fscanf( fp, "%d ", &tmp[i] );
//printf("tmp[%d]=%d",i,tmp[i]);
i++;
}
for ( i=0; i<MAXSIZE; i++ )
{
printf( "tmp[%3d]=%d\n", i, tmp[i] );
}
fclose( fp );
system("PAUSE");
}

giant7 2012-05-31
  • 打赏
  • 举报
回复
第一个:buf里面没有初始化,建议以后楼主都用memset初始化。
第二个:fgets的函数读取数据,从buf的第一个字节开始写入,读取到的就是要拷贝过去的。
qq120848369 2012-05-31
  • 打赏
  • 举报
回复
运气问题.
轻轻 2012-05-31
  • 打赏
  • 举报
回复
在c中使用类似这样char buf[128]的数组,如果不能确定是从第一个元素开始操作,那么就先使用memset初始化数组,如下
memset(buf,0,128);
c/c++中的字符串是以0结尾的
ouyh12345 2012-05-31
  • 打赏
  • 举报
回复
memset
W170532934 2012-05-31
  • 打赏
  • 举报
回复
看楼主的头像以为是小妹,结果来了个Last man。
第一个:buf里面没有初始化,但不是以'\0'结尾的啦。用strcat是把后面的字符串加到现在的字符串的末尾处。而字符串是以'\0'为结束标志的嘛。所以加到哪里就不知道了,反正你前面是乱码。
第二个:你用fgets的函数读取数据,从buf的第一个字节开始写入哦。那读取到的就是正常的字符串。肯定能正确输出

69,364

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧