我正在使用共享的 utils.cpp 撰寫服務器 - 客戶端應用程式。
因此服務器和客戶端使用(在 utils.h 中)預定義的方法:
int listening_socket(int port);
int connect_socket(const char *hostname, const int port);
int accept_connection(int sockfd);
int recv_msg(int sockfd, int32_t *operation_type, int64_t *argument);
int send_msg(int sockfd, int32_t *operation_type, int64_t *argument);
到現在為止還挺好。
但是由于 recv_msg() 只是回傳是否成功,我需要通過指標修改來處理傳輸的 operation_type 和引數。在這一點上,我有點迷路了。
我的目標是將方法引數(int32_t *operation_type 和 int64_t *argument 指標)設定為傳輸的值。在 server.cpp 中,我初始化了 int32_t * 和 int64_t * 以便將它們傳遞給 recv_msg() 方法(也嘗試給它們一個值,例如 = 0)。
服務器.cpp:
...
int32_t *operation_type; // with = 0; also Segmentation fault
int64_t *operation_type; // with = 0; also Segmentation fault
if (recv_msg(server_socket, operation_type, argument) == 0)
printf("In server.cpp: operation_type: %" PRId32 " and argument: %" PRId64 " \n", operation_type, argument);
在 utils.cpp 中,我試圖通過以下方式更改指標的值:
int recv_msg(int sockfd, int32_t *operation_type, int64_t *argument) {
// some buffer and read() stuff...
// trying to change pointer's value
operation_type = (int32_t *)1;
// also tried
*operation_type = 1;
// and same thing with the int64_t * argument pointer
int64_t argu = message.argument(); // also tried this
*argument = argu;
printf("In utils.cpp: operation_type: %" PRId32 " and argument: %" PRId64" \n", operation_type, argument);
以太我不改變點值,所以在方法中它們具有想要的值,但是在執行 recv_msg() 之后點值再次為 0 或者我得到一個Segmentation fault。
我了解指標和參考的基礎知識,但我習慣于 Java 并且不熟悉“*”和“&”前綴。
我的問題:如何修改在匯入方法中作為引數傳遞的指標,或者我準備好 int32_t 和 int64_t 接線?
uj5u.com熱心網友回復:
謝謝大家!我終于明白了,讓它發揮作用!
這里有視頻推薦:https ://www.youtube.com/watch?v=7HmCb343xR8
還有我實驗的虛擬代碼:
#include <stdio.h>
#include <stdlib.h>
int changePointer(int32_t *type, int64_t *argu);
int main(int args, char *argv[])
{
int32_t type = -1; // declare local varibales
int64_t argu = -1;
printf("\nPre-ChangePointer:\n type: %d at %d\n argu: %lld at %d\n\n",
type, &type, (long long)argu, &argu); // Debug print
changePointer(&type, &argu); // call mathod to change pointers value
printf("\nPost-ChangePointer:\n type: %d at %d\n argu: %lld at %d\n\n",
type, &type, (long long)argu, &argu); // Debug print
return 0;
}
int changePointer(int32_t *ptr, int64_t *ptr2) // ptr and ptr2 are copies of type_ptr and argu_ptr
{
*ptr = 2; // change value of type_ptr
*ptr2 = 2; // change value of argu_ptr
return 1;
}
uj5u.com熱心網友回復:
指標是應該用來指向一些分配的記憶體的變數。
在您的初始化中,您使指標指向 NULL,即沒有記憶體。
在那之后,你試圖改變什么都沒有的價值。這就是您遇到分段錯誤的原因。
您應該:
宣告一些區域變數并讓你的指標指向它們。就像是:
int32_t local_type_operation;
type_operation = &local_type_operation;
或者使用一些動態記憶體分配函式來分配一些記憶體指向(搜索一下malloc)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/480186.html
上一篇:帶有布爾指標的奇怪C 輸出
