私は以下のコードを持っています。C++でvoid *を構造体にキャストする
#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;"の後の3つのコード行とまったく同じことを行います。そうです。関数f()の何が問題なのか?
これはCではありませんが、C++! Cでは 'void *'を別のポインタ型にキャストすべきではありません。 – Olaf
@Olaf他の方法はC++ではありませんが、C –
@DieterLücking: 'cout << sb-><< endl'または' new byte [1000];はCですか? – Olaf