#Creating a Vector variable
47 messages · Page 1 of 1 (latest)
When your question is answered use !solved to mark the question as resolved.
Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.
my attempt so far:
typedef struct {
int length;
int *element;
} Vector;
Vector createVector(const unsigned int nLength)
{
float *array = malloc(nLength * sizeof(float));
}
I'm lost in the second part where I have to create a vector variable using a function
Can anyone give me a hint or sth? thanks
you need to allocate the pointer inside the Vector structure
huh
Initially you have an empty istance of a Vector, then you malloc the "element" inside of it when you call createVector and assign length to the nLength parameter
Then when you do destroyVector you must do a free of that Vector istance
I'm sorry I don't quite catch that
I'll give you a piece of code
sure
Without the solution because you need to understand
ofc
{
int size = 0; //empty
int* elements = NULL; //empty
} Vector;
void createVector(Vector* input, int size)
{
//malloc the input and insert the size
//you not need to return anything because you have the reference of the outside vector
}
int main()
{
Vector myVector;
createVector(&myVector, 10); //create my vector of 10 elements
}```
try to understand this
sure thanks a lot
you have your instance in the main, you call the createVector that fulls the vector instance
but in my hw it states that the input is only
unlike your function where u can have an input and size
i'll rewrite for this case
sure
{
int size = 0; //empty
int* elements = NULL; //empty
} Vector;
Vector createVector(const unsigned int nLength)
{
Vector myVector;
//malloc the elements inside the vector and insert the size
return myVector;
}
int main()
{
Vector myVector = createVector(10); //create my vector of 10 elements
}```
there you go
then after this try to delete it by yourself
sure
in visual studio code
cool
Hey for freeing the vector,
can I just free the whole variable like this?
void destroyVector(Vector vec)
{
free(*vec);
}
or should I free each of the members first then free the vec
you need to free the elements inside
because the Vector itself is in stack
elements is in the heap because you malloc it
oh
when you malloc something you need to free, if you don't malloc you don't need to free
that's the rule
Thank you and let us know if you have any more questions!
This thread is now set to auto-hide after an hour of inactivity