string is an array of characters ?

Feb 27, 2015 at 8:26am
we all know that string variables are characters arrays , so while we can assign value to char array very simply by :

1
2
  char x[10];
  x[5]=48;

but in string case this is no work !
here is this code , in char case it's working , but in string case it's not !

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include<iostream>
#include<string>
using namespace std;
int main()
{
	//Char case
	char x[10];
	for(int i=0;i<10;i++)
		x[i]=i+48;
	for(int i=0;i<10;i++)
		cout<<x[i]<<endl;

	//string case
	string str;
	for(int i=0;i<10;i++)
		str[i]=i+48;
	for(int i=0;i<10;i++)
		cout<<x[i]<<endl;
}
Feb 27, 2015 at 8:30am
In the "string case" you have an empty string. If you want the string to have 10 chars you should say so.

1
2
// Creates a string of length 10 with all characters set to '*'.
string str(10, '*');

http://en.cppreference.com/w/cpp/string/basic_string/basic_string
Last edited on Feb 27, 2015 at 8:31am
Feb 27, 2015 at 8:43am
but in the char array it's empty too !
why I have to fill string array with "*" ,and in char I haven't ?
remember that string has default size , you can see from :
1
2
3
4
5
6
7
8
#include<iostream>
#include<string>
using namespace std;
int main()
{
	string str;
	cout<<str.max_size()<<endl; //it returns 4294967294
}
Feb 27, 2015 at 9:20am
but in the char array it's empty too !

No, an array can't be empty.
1
2
3
// x is an array of 10 characters,
// the values of these chars are undefined.
char x[10];


why I have to fill string array with "*" ,and in char I haven't ?

You can use any other character you want. I just picked '*' out of the air because if I specify the size of the string in the constructor I also have to specify their value. I could also have used the resize function.
1
2
3
4
string str;
str.resize(10);
// which is equivalent to
string str(10, '\0');


remember that string has default size

The default size of a string is zero. The max_size() function just gives you an upper limit to what sizes can be handled. 4294967294 is the highest value that can be stored in an unsigned 32-bit number. In a 32-bit address space you will likely run into problems way before reaching that size because the string is not the only thing that use up memory.
Last edited on Feb 27, 2015 at 9:26am
Feb 27, 2015 at 2:46pm
Thank You!
Topic archived. No new replies allowed.