我有以下代码。
#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但不适用于某人! 函数f()与&#34; Struct_A * sa之后的三个代码行完全相同;&#34;确实。知道函数f()有什么问题吗?
答案 0 :(得分:0)
你是某人,但你应该传递一个指向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);