#include <iostream>
#include <string>
using namespace std;
int main() {
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
cout << cars;
return 0;
}
Why is it returning 0x7ffffcf9a010
when I output it?
#include <iostream>
#include <string>
using namespace std;
int main() {
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
cout << cars;
return 0;
}
Why is it returning 0x7ffffcf9a010
when I output it?
Yes, it will output that, the strange number you see is the address of the starting of the first element of the array, cars is implicitly converted to a pointer. By itself, it's an array rather than a pointer.
You want to do this,
#include <iostream>
#include <string>
using namespace std;
int main() {
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
//cout << cars[0]; // To print the first element
for(int i = 0; i < 4; i++)
{
// To print all the elements one by one with a new line in between each element
cout<<cars[i] << '\n';
}
return 0;
}
Output the name of raw array will return the first address of string array, which is the first element address too. Here's an example with std::string and int raw array.
#include<iostream>
int main() {
std::string str[] = {"This", "is", "a", "string"};
std::cout << str << std::endl; //output 0xc3585ff5b0
int arr[] = {1, 2, 3, 4, 5};
std::cout << arr << std::endl; //output 0xc3585ff590
return 0;
}
It outputs the hexadecimal address of the first element(0 index) of the array. Since array is a data structure that's why it outputs its address.
To correct the code you need to do this:
#include <iostream>
#include <string>
int main() {
std::string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
char string1[100]={"C-style string."};
std::cout << *cars<<"\n";
std::cout<<string1; // does not show hexadecimal address but why?
return 0;
}
Now this code will output 'Opel' as you required. The little asterisk next to the cars is known as the indirection operator. It is used to access the value the pointer is pointing to. Your confusion might be coming from the char array which can be outputted in one go using std::cout but the char array is an exception to the rule, the string array is not the same. Note(it is better use std::array and std::vector for modern C++ programming instead of the old fashioned array. )