q1:
The outputs:
World
World
The corresponding codes
#include
using namespace std;
void print_buffer(char *buffer[], int n){
for(int i = 0; i < n; i++){
cout << buffer[i] << endl;
}
}
int main()
{
char *buffer[2];
// initialize buffer with two strings "Hello" and "World"
// convert string to string char *
std::string temp = "Hello";
buffer[0] = &temp[0];
temp = "World";
buffer[1] = &temp[0];
print_buffer(buffer, 2);
return 0;
}
The intention for above codes is just to add the “hello” and “world” into the char pointer array. However, I cannot get the answer “hello world” I just wanted.
The fixed solution
#include
using namespace std;
void print_buffer(char *buffer[], int n){
for(int i = 0; i < n; i++){
cout << buffer[i] << endl;
}
}
int main()
{
char *buffer[2];
// initialize buffer with two strings "Hello" and "World"
// convert string to string char *
std::string temp = "Hello";
buffer[0] = &temp[0];
std::string temp2 = "World";
buffer[1] = &temp2[0];
print_buffer(buffer, 2);
return 0;
}