可能重复:
C 编程语言中数组的大小?
我将一个char
数组从一个函数 f1 传递给另一个函数 f2。在函数 f1 中,我使用sizeof
& 打印它的大小,结果是9
. 在第二个函数中,我再次使用与上面相同的语句打印它的大小,但这次它的结果是8
. 事实上,我并没有在打印两个值之间使用这个数组。当我尝试在另一台笔记本电脑上运行相同的代码时,对于第二个函数,它会产生4
.
从这个问题可以清楚地看出为什么我得到 4,但为什么我在另一台笔记本电脑上得到 8。
为什么会这样?
我的整个代码太大了,所以我只分享基本部分:(这里我正在谈论的数组是plid
,我login
从第一个函数调用函数。由于它们的长度,我没有分享完整的函数。logp, errorp..
这些是我自己编写的写入文件的函数,我最后分享了。)
f1:
char choice[1], plid[9];
int choice_len = sizeof(choice);//this is importnat becz recvall takes ppointer to int
int ret;
logp(identity,0,0,"receiving the first choice of the client");
if(recvall(fd, choice, &choice_len, 0) != 0){ //whether want to play(login), or as audience(no login)
logp(identity,0,0,"Error receiving the first choice of the client");
}
logp(identity,0,0,"Entering the choice Select switch");
switch(choice[0])
{
case 'a':
sprintf(buf, "plid_len(%d), username_len(), plid - %d",sizeof(plid), plid);
logp(identity,0,0,buf);
logp(identity,0,0,"User entered the choice 'a' and calling login");
if( (ret = login(fd, plid)) == 0){
sprintf(buf,"Player id is %s and Contacting player",plid);
logp(identity,0,0,buf);
contactPlayer( plid, fd);
logp(identity,0,0,"Contacted To player succesfully");
}else{
f2:
int login(int fd, char* plid){
char loginInfo[25], username[9], password[16];
int loginInfo_len = sizeof(loginInfo);
int ret;
char identity[IDENTITY_SIZE], buf[100];
sprintf(identity, "DISPATCHER-login-fd: %d -", fd);
sprintf(buf, "plid_len(%d), username_len(%d), plid - %d",sizeof(plid), sizeof(username), plid);
logp(identity,0,0,buf);
logp(identity,0,0,"Calling recvall to recv login credentials");
if ((ret = recvall(fd, loginInfo, &loginInfo_len, 0)) != 0) {
errorp(identity,0,0,"Unable to recv login credentials");
debugp(identity,1,errno,NULL);
}
日志文件输出:
__LOG__ | Wed Dec 26 19:21:34 2012 | Where - DISPATCHER-SocketHandler-fd: 6 - | LogMsg - Entering the choice Select switch
__LOG__ | Wed Dec 26 19:21:34 2012 | Where - DISPATCHER-SocketHandler-fd: 6 - | LogMsg - plid_len(9), username_len(), plid - -1314939296
__LOG__ | Wed Dec 26 19:21:34 2012 | Where - DISPATCHER-SocketHandler-fd: 6 - | LogMsg - User entered the choice 'a' and calling login
__LOG__ | Wed Dec 26 19:21:34 2012 | Where - DISPATCHER-login-fd: 6 - | LogMsg - plid_len(8), username_len(9), plid - -1314939296
__LOG__ | Wed Dec 26 19:21:34 2012 | Where - DISPATCHER-login-fd: 6 - | LogMsg - Calling recvall to recv login credentials
__LOG__ | Wed Dec 26 19:21:34 2012 | Where - access-recvall | LogMsg - Successfully recved the complete data