+ 2
Can we store a structure having a dynamic array in? If yes then how? Plz... help...
For.eg. typedef struct { int* arr; } Data; Data obj; obj.arr = (int*)malloc(2*sizeof(int)); obj.arr[0] = 0; obj.arr[1] = 1; Now i want to store this obj object of structure data...
15 odpowiedzi
+ 2
Sp, here's a quick fix to make dynamic arrays work. Also, would be cool to see your game when you get it done :)
https://pastebin.com/FPH9tnWj
+ 2
You want to store this data to file? You need to use something like fwrite:
https://overiq.com/c-programming-101/fwrite-function-in-c/
+ 2
Sp Maurya
This is just an idea,
Maybe you can add 'count' field into the 'Data' struct. The 'count' field defines how many elements have been allocated for 'arr' field. When saving to file you use 'count' field value as a counter in a loop, so you know how many times for-loop should run, writing each 'arr' element into the file.
+ 2
You're welcome :) C-way of doing things may take some time to get familiar with, but I believe it pays off in the long run.
+ 1
Sp, gotcha. Follow Ipang's advice. That should do the trick.
+ 1
Can you share your program so we can take a look?
+ 1
Daniel i'm working on a project so it is quite large but i will share the important part of it
+ 1
Here is my code
Goto the link....
https://pastebin.com/9C3BNg3T
+ 1
Awesome, dude now i get it what was the problem... I was saving the pointer, so we have to save the data one by one and also read it one by one... And here the magic is memcpy which i was not using...
Thank you very very much.... 😊
I need to dig more to know the memory concepts more...
+ 1
Also Ipang Thank you, you were also saying the similar solution but i wasn't able to get it how it will be done...
0
Daniel actually i know how to save file... The problem is that in Data there is a pointer to the elements of dynamic array...
So when i save the file only that pointer get saved... And again when i read that file i lose the data...
0
Daniel i did that already too...
😂😂😂
I think i need to do it in c++,
Using vectors...
0
Also this code is working when i don't use a dynamic array i.e. by using static array...
https://pastebin.com/TuGiB4qg