use*_*772 3 c sockets pointers client-server
我的部分代码:
int server_sockfd, client_sockfd; //socket file descriptors of client and server
// ... some code
if(pthread_create(&vlakno, NULL, handle_client, (int *) client_sockfd) != 0) {
perror("Error while creating thread.");
}
Run Code Online (Sandbox Code Playgroud)
我正在收到"警告:从不同大小的整数转换为指针[-Wint-to-pointer-cast]"
我的功能原型:
void *handle_client(void *args);
Run Code Online (Sandbox Code Playgroud)
我发现了这个问题:
链接
第一个答案说他应该使用intptr_t而不是int.
我有两个问题:
在我的情况下int和intptr_t
有什么区别?
我该怎么办?
我有2个想法:
第1 :(更改文件描述符的类型)
int server_sockfd, client_sockfd; //socket file descriptors of client and server
// ... some code
if(pthread_create(&vlakno, NULL, handle_client, (intptr_t *) client_sockfd) != 0) {
perror("Error while creating thread.");
}
Run Code Online (Sandbox Code Playgroud)
或第二个想法:(仅在铸造函数pthread_create中更改类型)
intptr_t server_sockfd, client_sockfd; //socket file descriptors of client and server
// ... some code
if(pthread_create(&vlakno, NULL, handle_client, (int *) client_sockfd) != 0) {
perror("Error while creating thread.");
}
Run Code Online (Sandbox Code Playgroud)
编辑:
在函数handle_client中我想这样做:
int clientSocket;
clientSocket = (int)args;
Run Code Online (Sandbox Code Playgroud)
我真的很抱歉用户cnicar或类似的东西......他不幸地删除了他的答案,但没关系.
他的解决方案是使用(void*),它首先输出相同的错误,但它可能导致eclipse的不良行为:(所以对他的消息:
好的,谢谢它现在看起来很好...... Eclipse仍然抛出这个警告但是当我转向它打开和关闭两次使用你的编辑编辑好:)非常感谢
小智 6
你已宣布client_sockfd为int.你不应该int *这样做.
使用&运营商,获得的地址client_sockfd,而不是如果你打算给一个指针到client_sockfd:
pthread_create(&vlakno, NULL, handle_client, &client_sockfd)
// ^ & operator
Run Code Online (Sandbox Code Playgroud)
要注意一生client_sockfd,它必须比线程更长,以防止竞争条件(见评论).
之间的差int和intptr_t的是,int是指以保持的整数,而intptr_t是指在一个整数的形式持有的地址.intptr_t保证能够保持指针,而int不是.
如果你的目的是传递价值的client_sockfd,将其转换为intptr_t:
pthread_create(&vlakno, NULL, handle_client, (intptr_t)client_sockfd)
Run Code Online (Sandbox Code Playgroud)
(int *) client_sockfd
Run Code Online (Sandbox Code Playgroud)
client_sockfd不是指针。它是一个int,与 的大小不同int *。它正在告诉你这一点。
最后一个参数是pthread_create()a void *,它是指向要传递到该特定线程的数据的指针。您似乎正在尝试将 的整数值转换client_sockfd为指针并传递它。这通常不是你会做的事情,但如果你真的想要并避免警告,那么你需要使用与指针大小相同的东西,这就是intptr_t给你的。在您的系统上,很可能int是 4 个字节,intptr_t(和void *)是 8 个字节,但这取决于平台。虽然您可以安全地从 32->64->32 位转换,但编译器会警告您有不同的大小。