我有这个代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Library stuff
typedef struct {
int x, y;
} _TYPE_position;
typedef struct {
char image[32];
_TYPE_position position;
} _TYPE_object;
_TYPE_object *object;
int createObject(const _TYPE_object *insertionObject);
int createObject(const _TYPE_object *insertionObject) {
int index;
_TYPE_object *newObjectPtr = realloc(object, sizeof(*object) + sizeof(_TYPE_object));
if(newObjectPtr != NULL) {
object = newObjectPtr;
index = sizeof(*object) / sizeof(_TYPE_object) - 1;
strcpy(object[index].image, insertionObject->image);
object[index].position = insertionObject->position;
}
else {
index =- 1;
}
return index;
}
// Demo program
int main(void) {
_TYPE_object smile = {
"smile.png", { 112, 80 }
};
int smileIndex = createObject(&smile);
if(smileIndex == -1) {
printf("Error allocating memory for smile object");
while(1);
}
smile.position.x = 55; // Does nothing since the object does not point here for some reason
int i;
for(i = 0; i < sizeof(*object) / sizeof(_TYPE_object); i++) {
printf("Create %s at { %d, %d }\n", object[i].image, object[i].position.x, object[i].position.y);
}
return 0;
}
它有点工作。似乎 object 没有指向 _TYPE_object ,而是创建了它的精确副本。
有没有办法让对象数组指向对象,而不仅仅是重新创建它们。所以在上面的例子中有smile.position.x = 55; 实际更改打印的值。