For the below code
struct orderSlip
{
char source[64];
char destination[64];
char item[64];
int position;
};
//global
struct orderSlip data[100];
Is there another way of printing out the data for each element other than these methods below:
printf("%s\n",data[0].source);
printf("%s\n",data[0].destination);
printf("%s\n",data[0].item);
printf("%i\n\n", data[0].position);
printf("%s\n",data[1].source);
printf("%s\n",data[1].destination);
printf("%s\n",data[1].item);
printf("%i\n", data[1].position);
etc
for(int n = 0; n< 3; n++)
{
printf("%s\n",data[n].source);
printf("%s\n",data[n].destination);
printf("%s\n",data[n].item);
printf("%i\n\n", data[n].position);
}
For deleting and adding, do I have to make a dynamic array of structs? If so, what would be the simplest syntax to do that? Something like this c++ code
int * bobby;
bobby = new int [5];
delete bobby[5];
but in C? I'm guessing it has do with malloc and free
"For deleting and adding, do I have to make a dynamic array of structs? If so, what would be the simplest syntax to do that? Something like this c++ code"
Not if you know that you will never have more than x amount of items or at least check to make sure you aren't exceeding what you planned was the max. Then you can use your static array.
Adding only requires you to have a variable that keeps track of how many items are in the array:
Deleting from a static array would require a for loop that would move the items above it down one and decrementing the int keeping track of the number of items.
You could simplify printing the struct by passing it to a function that does the work.
or
optionally
or
and
One way is to allocate each element in your array and just keep an array of pointers
(calloc will make sure memory is zero:ed from the start)
everytime you add a new struct:
and when you don't need any longer
You can also change the size of data by using realloc, see
If you don't need to access the array using index, you could instead consider another type of data structure like a linked list to be truly dynamic.