Proper Pointer use

I wrote a program to pass a large string to make passing it a point, since passing a number or two isnt really pointer worthy so instead i decided on passing a huge string, so is this how i would use a pointer? After reading one of these books I understand pointers pretty good, but I cant ask the book questions so I want to make sure i'm doing this right. I'm pretty positive i did though.

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
#include <iostream>
#include <sstream>

using namespace std;

void DisplayText(string *text);

int main()
{
    string text = "Hello World ";

    for(int i = 0; i < 10; i++)
    {
        text += text;
    }

    string *pText = &text;

    DisplayText(pText);

    return 0;
}


void DisplayText(string *text)
{
    cout << *text << endl;
}
Last edited on
Yes, you may pass pointer like this since the compiler doesn't complain, but with strings you shouldn't us pointer. Instead use const &:
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
#include <iostream>
#include <sstream>

using namespace std;

void DisplayText(const string &text); // Note

int main()
{
    string text = "Hello World ";

    for(int i = 0; i < 10; i++)
    {
        text += text;
    }

    DisplayText(text);

    return 0;
}


void DisplayText(const string &text) // Note
{
    cout << text << endl;
}
This is safer since a pointer can be null or worse: uninitialized.
The code given by coder777 also has the additional benefit that you can pass string literals to the function directly.

 
DisplayText("abc...");
ok cool, and yeah i know i could have used the pass by reference operator, but i just wanted to familiarize myself with pointers. A better example that i should have used is something like an image in use with a graphics library which i did once. But even then I could pass the image using the address of operator right?
bump
@Ch1156 hello can you tell me what book you are reading?
thanks.
You can always pass by reference instead of pointer except if you want to allow a null pointer to be passed to the function.

In your code it's a bit unnecessary to create the pointer as a variable. You could just pass the pointer that you get from the & operator to the function directly. DisplayText(&text);
Last edited on
Topic archived. No new replies allowed.