关于结构体数组赋值的问题

#include<time.h>#include<stdlib.h>#include<stdio.h>#include<string.h>#include<unistd.h>struct time { char ctime[19];}T[5];char current[19];char getTime(){ timespec time; clock_gettime(CLOCK_REALTIME, &time); //获取相对于1970到现在的秒数 tm nowTime; localtime_r(&time.tv_sec, &nowTime); sprintf(current, "%04d-%02d-%02d-%02d:%02d:%02d", nowTime.tm_year + 1900, nowTime.tm_mon+1, nowTime.tm_mday, nowTime.tm_hour, nowTime.tm_min, nowTime.tm_sec);}int main(){ for(int i=0;i<5;++i) { memset(current,0,sizeof(char)*19); getTime(); strcpy(T[i].ctime,current); printf("t[%d], ctime=%s, currtime=%s\n",i,T[i].ctime,current); sleep(2); } printf("t[0]=%s\nt[1]=%s\nt[2]=%s\nt[3]=%s\nt[4]=%s\n",T[0].ctime,T[1].ctime,T[2].ctime,T[3].ctime,T[4].ctime); return 0;}请问为什么跑出来的结果是这样的?求大神解答!

第1个回答  2018-04-12
我来分析一下,
struct save_account//保存登录帐户密码
{
char account[10];
char password[10];
}users[10] = {0};
这个我理解是定义了一个结构数组users[10], 并初始化为0.
也就是说user[]数组有10个元素,每个元素是上面的这样一个结构.

下面来看strcpy这个函数,是标准c库函数, 原型是
char * strcpy(char * strDest,const char * strSrc);

这个函数是把src所指由NUL结束的字符串复制到dest所指的数组中。
所以用这个函数,字符串必须以NULL结束,否则可能会发生访问越界. 而两个参数应该是数组首地址,所以如果要用这个函数,应该这样写strcpy(users[10].account,a);
可以构造一个循环,代码如下:
for(i = 0; i < 10;i++)
{
strcpy(users[i].account,a);
strcpy(users[i].password,pwd);
}

至于你提出的方法2的直接给数组附值,是不合法的.本回答被网友采纳
相似回答