Help With string and pointers

Hey I was wondering if I could get some help. I just started to learn about pointers. And I seem to get it, i just cant seem to get why this code wont work. It does nothing useful I just wanted to see if I could create two function and make a third one using pointer so I could call both in this third function. This is what I came up with:

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
#include "stdafx.h"
#include<iostream>
#include<string>
#include<Windows.h>
using namespace std;

int color(int number) //For changing color of the console
{
	HANDLE color;
	color = GetStdHandle(STD_OUTPUT_HANDLE);
	SetConsoleTextAttribute(color,number);
	return number;
	

}

string shout(string sentence) //For saying a word
{
        cout << sentence;
	return 0;

}

void all(string &refrence,int &number, string (*pointer)(string),int (*voidpointer)(int)) //To call both the color and shout function in one function
{
	
	
	int typecolor;
	typecolor = (*voidpointer)(number);
	string phrase;
	phrase = (*pointer)(refrence);
}


int _tmain(int argc, _TCHAR* argv[])
{
 string word;
 cout <<"Enter word > ";
 getline(cin,word);
 int colorneed = 5;
 all(word,colorneed,shout,color);


	return 0;
}



My code does it jobs it says the word that the user entered and give it in the color purple. But then it crashes and gives me this error:


Debug Assertion Failed!

Program: ........
File: c:\program files (x86)\microsoft visual studio 10.0\vc\include\xstring
Line: 930

Expression: invalid null pointer
For information on how your program can cause an assertion
failure, see the Visual C++ documentation on asserts.


If I take out the string part and just keep the color function my all function can call upon it no problem. But adding the string part cause the error shown above to show. Is there something I must know about string pointers to make this work? Any help is appreciated.

Solved it by changing this
1
2
3
4
5
6
7

string shout(string sentence) //For saying a word
{
        cout << sentence;
	return 0;

}


to:
1
2
3
4
5
6
string shout(string sentence) //For saying a word
{
        cout << sentence;
	return sentence;

}



But I have no idea though on why it worked can some explain why it will no longer crash?
The string constructor doesn't like null strings (=0 or NULL)

(returning 0 triggers the const char* form of the constructor with 0))

It's the same for string::assign() with a null char* string

If you want a function to return an empty string, you can use

1
2
3
4
5
string shout(string sentence) //For saying a word
{
        cout << sentence;
	return string();
}


or

1
2
3
4
5
string shout(string sentence) //For saying a word
{
        cout << sentence;
	return "";
}



(I prefer the former, as it's more explicit.)

Andy
Last edited on
Thanks for the help it make sense now
Topic archived. No new replies allowed.