How to concatenate a '*' (star character) to a TCHAR* or char*

Every time I try to do this will concludes with a crash:

test.exe has stopped working

A problem caused the program to stop working correctly.
Windows will close the program and notify you if a solution is
available.


as shown in the popped up message window

My code is really simple. It's going to add a '*' onto the end of a existing string. The string can be char* or wchar_t*. I'm using a very safe way to do it.
Here is my code (forget about the comments):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
#include <stdlib.h>
#include <string>

#include "atlbase.h"
#include "atlstr.h"
#include "comutil.h"

#include <strsafe.h>

#include <iomanip>
#include <windows.h>
#include <tchar.h>
#include <wchar.h> 
#include <stdio.h>
#include <strsafe.h>
#include <malloc.h>


#define MAX_PATH_CONG 260

//#ifdef _DEBUG			// if in debug mode
//#define new DEBUG_NEW	// replace the memory allocation method to prevent memory leakage
//#endif				// end of "if in debug mode"

using namespace std;

int main()
{
	//wchar_t* ws1[2] = { _T(""), _T("") };
	//wchar_t* ws2 = _T("..\\data\\*");
	//ws1[1] = ws2;

	char* cs1 = "";
	char* cs2 = "..\\data\\*";
	cs1 = cs2;

	cout << "\n cs1 = [" << cs1 << "] \n";
	
	char* cs3 = cs1;
	size_t length_cs3 = strlen ( cs3 );
	cs3[ length_cs3 - 1 ] = '\0';
	cout << "\n After appending '*' : \n";
	cout << "\n cs1 = [" << cs1 << "] \n";
	cout << "\n cs3 = [" << cs3 << "] \n";

	/*
	wcout << _T("\n ws1[1] = [") << ws1[1] << _T("] \n");
	ws[1] += '*';
	cout  << "\n After appending '*' \n";	
	*/
	// wcout << _T("\n ws1[1] = [") << ws1[1] << _T("] \n\n\n");
}

1
2
3
	char* cs1 = "";
	char* cs2 = "..\\data\\*";
	cs1 = cs2;


pointers are not strings.

What's more, string literals are constant. So char* cs1 = ""; shouldn't compile (although some compilers let it slide -- even though they shouldn't!)

Lastly, use '/' for a directory separator, not "\\"


To make this simpler, use strings:

1
2
3
4
5
6
7
8
9
10
string foo = "whatever";
cout << "foo=" << foo << "\n";

// append '*' to the end
foo += "*";

// or
foo.push_back('*');

cout << "foo after appending=" << foo;
Last edited on
Topic archived. No new replies allowed.