Say I have declared char *array[size] in my program and put some strings in it. If I assign something again to them, they don't replace the previous contents but they keep on appending on the previous contents. How do I correctly clear/reset all of its contents?
void function(char* action)
{
const int myMainArrSize = 3;
char *myMainArr[myArrSize];
char *myArrOne[] = {"String 1", "String 2", "String 3"};
char *myArrTwo[] = {"Another String 1", "Another String 2", "Another String 3"};
if(strcmp(action, "action1")==0)
{
for(int i=0;i<myMainArrSize;i++)
{
myMainArr[i] = myArrOne[i];
}
}
if (strcmp(action, "action2")==0)
{
for(int i=0;i<myMainArrSize;i++)
{
myMainArr[i] = myArrOne[i];
}
}
}
Best Answer
You have
That makes
array
an array of pointers. Specifically,array
is an array ofsize
pointers. Each element in the array (array[0]
toarray[size-1]
) is of typechar *
.I think it would help if you understood how
array
works:Each of the boxes above represents a pointer, and the arrows are where they are pointing to. The storage for them is not yet assigned to, so they are just "out there", pointing nowhere useful. You can either create memory for them (
malloc()
etc., in C,new[]
in C++), or you can point them to some existing location.You say:
It is not clear how you are putting "strings in it". Do you mean you are storing strings in
array[0]
..array[size-1]
? How? Are you assigning literal strings to them? Something like:If you are doing that, then, you can reassign to the pointers and the strings wouldn't append. In other words, if later in your program you do:
you are reassigning the pointer
array[0]
to point to"Another string"
, and thus you're not appending.So, in short, we need to see more code, and you may need to understand pointers and arrays better.
Edit: Based upon your edit, the pointers
myMainArr[i]
(fori=0
toi=3
), do get reassigned to the corresponding elements frommyArrOne
ormyArrOne
(not a typo!), depending upon the contents ofaction
. So, if you printed them (for example,printf("%s\n", myMainArr[0]);
), you shouldn't see any strings being appended. Also,myMainArr
is local to your functionfunction
, so it gets destroyed when your function returns. (Incidentally, your choice of the namesarray
for an array andfunction
for a function make it harder to be unambiguous when answering the question!)If you are having a problem, please post a complete, minimal, compilable code that shows the problem.