<分区>
Possible Duplicate:
Sizeof an array in the C programming language?
我正在将一个 char
数组从函数 say f1 传递到另一个函数 f2。在函数 f1 中,我使用 sizeof
打印它的大小,结果是 9
。在第二个函数中,我再次使用与上面相同的语句打印它的大小,但这次它的结果是 8
。事实上,我并没有在打印这两个值之间使用这个数组。当我尝试在另一台笔记本电脑上运行相同的代码时,第二个函数的结果是 4
。
由此可见question这就是为什么我得到 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