reseting an array, possible?

can you reset an array? For example, i create an char array that reads hello. I print it out. Now I want to give this array another string of chars. But as i already gave this array the string of chars 'h e l l o', I cant give this array new string of chars. I could create a new array, but for certain reasons that I dont want to explain you guys, id really prefer it, if you could just reset the array
If your array has no qualificator const you may assign a value to any element of the array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <cstring>

int main()
{
   char s[] = "hello";

   std::cout << s << std::endl;

   std::strcpy( s, "world" );
   
   std::cout << s << std::endl;

   s[0] = 'L';

   std::cout << s << std::endl;

   return ( 0 );
}


I'd like to append that to make a character array that is considered as a string empty it is enough to assign '\0' to its first element.

s[0] = '\0';
Last edited on
you can do what vlad says, but only if the other string has equal or less chars than the very first string you assigned the char array to
If that is too much of a restriction you could use dynamic allocation (prefer to wrap it with std::vector or std::string)
This is a quite generic but also not very hard problem.

Be general to 'reset the array', just 'memset(yourarrayptr, 0, yourarraysize);'.

As you are talking about char array as string, just set your variable of representing the length of the array to 0, simply as 'yourarraysize = 0', and use your array again with setting one new value of length to 'yourarraysize'.

@mathcat
As you are talking about char array as string, just set your variable of representing the length of the array to 0, simply as 'yourarraysize = 0', and use your array again with setting one new value of length to 'yourarraysize'.


It is a wrong statement because setting some variable "representing the length of the array to 0" does not allow to use this array in C string functions as an empty array. There is no any need to introduce one more variable that will contain the length of an array. It is enough to set the first element of a character array to zero as I show in my previous message.
Topic archived. No new replies allowed.