Home > database >  How to delete string array from a struct in c
How to delete string array from a struct in c

Time:02-05

I wonder how to delete string array from a structure.

For example I have a structure and an array defined this way:

struct dataofcall {
    char day[25];
    char country[25];
    char startofthecall[6];
    char endofthecall[6];
};

dataofcall call[MAX];

Then I ask user to input a number of calls that he wants to enter: for example: 3.

Then with a for cycle user enters information about 1, 2, and 3 call. Like this:

Monday Luxembourg 22:12 22:15
Tuesday Germany 12:21 14:16
Tuesday France 09:08 23:23

And call[0] will look like this:

call[0].day[25] = "Monday";
call[0].country[25] = "Luxembourg";
call[0].startofthecall[6] = "22:12";
call[0].endofthecall[6] = "22:15";

call[1] will look like:

call[1].day[25] = "Germany";

etc.

So, now I need to delete information from call, for example 2 and 3, that 1 and if are any other calls, will be untouched.

I just don't understand how can I delete it, not how to enter information about calls or whatever. Just want to ask help for algorithm or small cycle that will help me in deleting an string from struct array.

I tried to do this:

strcpy(call[0].country, "Data is deleted.");

But it looks somewhat incorrect, like it should be better way in doing it, that I can't find.

CodePudding user response:

You cannot delete (as in free the memory), but you can do something like

call[0].country[0] = '\0';

This makes the string handling functions see call[0].country as being an empty string because the first character is now a \0 which is the string terminator.

CodePudding user response:

If the array was declared with automatic or static storage duration:

dataofcall call[MAX];

then there's no way to delete it.

The array will cease to exist (in case of automatic storage duration) when the it reaches the closing brace of the block it was declared in. Static storage duration, however, exists for the lifetime of a program and wouldn't go out of scope.

If you instead, allocated the memory dynamically on the heap with something like this:

struct dataofcall **call = malloc (MAX * sizeof (struct dataofcall);

Then you can delete (or free) the memory allocated from the heap with a call to free().

free (call);
  • Related