how strcat works

This doesn't work

1
2
3
4
5
6
7
8
9
10
      char* greetings = "";
      strcat (greetings,"hello");
      strcat (greetings," world");
      strcat (greetings,"!");
      cout << greetings << endl;

      getchar ();
	
	
      return 0;


what is the reason ?
Thank you
Take a look at the example here -> http://cplusplus.com/reference/clibrary/cstring/strcat/

You need to provide some space for your string to grow. You only provide a char pointer. When strcat operates on that, it probably overwrites important data and your program crashes as a result.

A better alternative would be to use std::string:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>
using namespace std;

int main()
{
    string greetings = "";
    greetings+="hello";
    greetings+=" world";
    greetings+="!";
    cout << greetings << endl;

    cout << "\nhit enter to quit...";
    cin.get();
    return 0;
}

More info on std::string -> http://cplusplus.com/reference/string/string/
Topic archived. No new replies allowed.