Reputation: 1305
I have four arrays that are built from reading in a file:
file_name[r] // char array (defined as file_name[10][10])
file_num[r] // int array
file_scale[r] // float array
file_source[r] // int array
So I would like to know, how can I clear/empty these arrays so that they are emptied before they are populated?
Upvotes: 0
Views: 261
Reputation: 7873
What you can do is set all the array to a definite value, but theyre is no "empty" array.
What you can do is, at the declaration:
char file_name[10][10] = {{0}};
int file_num[r] = {0};
float file_scale[r] = {0};
int file_source[r] = {0};
so that every variable of every array is 0.
Upvotes: 1
Reputation: 11
If you need to empty them only when the program starts, how to make them empty depends on the compiler you use, since it depends on the initialization code the compiler puts before executing your code. Usually
int someArray[10] = {0};
char charArray[100] = {0};
is initializing array to 0. This work also when you declare a local array into a function, that is placed on the stack and reset to 0.
For resetting a previously created array to 0's at runtime there is a standard C function that all compilers I used until now are implementing:
memset(myArray,0,sizeof(myArray));
of course you need to #include <string.h>
as already said.
Upvotes: 1
Reputation: 71019
Any global array will be zero initialized when it is declared. For other cases you can use memset from the header <string.h>
like so:
memset(file_name, 0, sizeof(filename));
Also for any array you can zero initialize it, when you declare it like so:
int a[r] = {0};
Although here you explicitly set the value only for the first element, the remaining ones are filled with 0 by standard.
Upvotes: 4
Reputation: 6925
what does "empty an array" mean? an array has always the same size. it cannot be emptied.
so you have to store the acutal length of your data in a separate variable like int used
.
then its easy to "empty" the array by setting this variable to 0.
if you want to set defaults then you may memset
the memory.
this is easy if you group the data in a POD-structure.
MyType myType;
memset(&myType, 0, sizeof(myType));
Upvotes: 1