[英]casting void* to struct * in C++
我有以下代碼。
#include <iostream>
using namespace std;
typedef unsigned char byte;
typedef struct {
unsigned int a;
unsigned int b;
} Struct_A;
void* malloc_(size_t s, byte* heap, int *next) {
int old = *next;
*next = *next + s;
return heap + old;
}
void f(Struct_A *sa, byte* heap, int *next) {
sa = (Struct_A*) malloc_(8, heap, next);
sa->a = 10;
sa->b = 20;
}
int main() {
byte *heap = new byte[1000];
int next;
next = 0;
Struct_A *sa;
sa = (Struct_A*) malloc_(8, heap, &next);
sa->a = 100;
sa->b = 200;
cout << sa->a << endl;
Struct_A *sb;
f(sb, heap, &next);
cout<< sb->a <<endl;
return 0;
}
該代碼適用於 sa 但不適用於 sb !!! 函數 f() 在“Struct_A *sa;”之后的三行代碼中執行完全相同的操作做。 知道函數 f() 有什么問題嗎?
你傳遞 sb,但你應該傳遞一個指向 sb 的指針並聲明 f 有一個額外的間接:
void f(Struct_A **sa, byte* heap, int *next) {
*sa = (Struct_A*) malloc_(8, heap, next);
(*sa)->a = 10;
(*sa)->b = 20;
}
int main() {
Struct_A *sb;
f(&sb, heap, &next);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.