I have two structs:
struct Parent {
struct *Child child; // Pointer to a child
}
struct Child {
int id;
}
I wish to init an array of 'Parent'
int size = 2;
struct Parent *parents = (struct Parent*) malloc(sizeof(struct Parent) * size);
this breaks when runs.
Any solution for this?
I want to initialize in such way:
struct Parent {
struct *Child child = nullptr; // Points to null upon initialization.
}
Don't mix C and C++; compile your C code using a C compiler, your C++ code using a (compatible) C++ compiler then link it using the linker , as you would with any other language.
Don't use malloc
in C++; use new
instead .
Don't cast malloc
(or other void *
values) in C .
Don't use int
for size values in C; use size_t
, instead.
Don't use nullptr
in C; it doesn't exist. Use NULL
instead.
Since you mentioned you wanted C - you could use memset
to initialize the memory (including the child
pointer) to all zeroes.
size_t size = 2 * sizeof(struct Parent);
struct Parent* parents = (struct Parent*)malloc(size);
memset(parents, 0, size);
This will initialize the entire parents
array to all zeroes. Otherwise it will be initialized to whatever happened to be in the memory when it was allocated.
The proper solution in C++ will be significantly different (use new[]
and constructors to initialize the structs).
In C
I use calloc()
instead of malloc()
.
Because, calloc()
zeroes the memory returned, malloc()
doesn't.
But if you want to zero memory after allocation, I personally prefer bzero()
because it's unambiguous about it's purpose and takes one fewer argument than memset()
does. I would generally use memset()
can fill with non-zero values for that reason.
Chris Vig brings up a good point, but I think what you were tying to do was this
#include <iostream>
struct Child {
int id;
};
struct Parent {
struct Child* c ; // Pointer to a child
};
int main() {
int size = 2;
struct Parent *parents = (struct Parent*) malloc(sizeof(struct Parent) * size);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.