When declaring strings like this:
char *mypointerorarray[] = {"string1", "string2", "string3"};
Is this a pointer to several arrays or an array of pointers to strings?
Also how would I go about removing this from memory?
When declaring strings like this:
char *mypointerorarray[] = {"string1", "string2", "string3"};
Is this a pointer to several arrays or an array of pointers to strings?
Also how would I go about removing this from memory?
It's an array of pointers to char
. It will contain the addresses of the string literals "string1"
, "string2"
, and "string3"
.
The memory for the string literals is allocated at program startup and held until the program terminates.
If the array is declared outside of any function (at file scope) or is declared within a function or block with the static
keyword, then the memory for it (enough to hold 3 pointer values) will also be allocated at program startup and held until the program terminates.
If the array is declared within a function or block, then the memory for it is allocated on block entry and released on block exit, logically speaking; in practice, memory for all auto
variables within a function is set aside at function entry, even if the lifetime of the variables doesn't extend over the whole function. For example, given the code
void (foo)
{
int x;
int y;
...
for (int i = 0; i < 100; i++)
{
int j;
int k;
...
if (condition())
{
char *arr[] = {"string1", "string2", "string3"};
...
]
...
}
...
}
the lifetime of arr
is limited to the inner if
statement, the lifetimes of i
, j
, and k
are limited to the loop, and only x
and y
have lifetimes over the whole function. However, all the implementations I'm familiar with will allocate the memory for x
, y
, i
, j
, k
, and arr
on function entry and hold it until the function exits.
mypointerorarray
is an array of 3 pointers. However, elements of this array happen to point to beginnings of string literals. Each string literals is by itself an array.
You cannot "remove it from memory", since you did not allocate it in the first place. Depending on where your mypointerorarray
is defined, it will have either static or automatic storage duration. It will be "removed from memory" automatically once its storage duration ends.
char *mypointerorarray[] = {"string1", "string2", "string3"};
the above declaration is array of character pointers. means in this case you will get three character pointers, each pointer is pointing to corresponding string literals. i.e char *mypointerorarray[0] -> "string1", char *mypointerorarray[1] -> "string2" and char *mypointerorarray[2] -> "string3".