0

I'm trying to make an array of strings, and connect them with a linked list. The problem is we can only use arrays. The instructor said we can't use templates, vectors etc. Those are the only ways I've found to be able to do this. I don't think this is even a linked list, he wants our arrays to be handled in the parallel instead of pointing to the next element in line.

#include <iostream>
#include <string>

using namespace std;

int main ()
{
    string names [4] = {"Dick", "Harry", "Sam", "Tom"};
    string *nameptr[4];

    for(int x = 0; x < 4; x++)
    {
        *nameptr[x] = names[x];
        cout << nameptr[x] << "  ";
        cout << &nameptr[x] << endl;
    }
}

What's wrong with this code? What am I missing?

I'm lost, if anyone could shed some light on this it would be great.

2 Answers 2

4

Your question isnt' clear but to make your code run.

Try update

*nameptr[x] = names[x];

to

nameptr[x] = &names[x];
Sign up to request clarification or add additional context in comments.

Comments

3

string names[4] = {"Dick", "Harry", "Sam", "Tom"}; is an array of std::string objects. string *nameptr[4]; is an array of pointers to std::string objects.

To initialize pointer, you need to assign the address it will point to to it: nameptr[x] = &names[x];

Dereference operator (*) is used when you want to access the memory where your pointer points to. For example printing the string that nameptr[x] points to: std::cout << *nameptr[x];


Explanation of why your program "has stopped working": You've declared string *nameptr[4];, i.e. the array of pointers, but you didn't initialize it. Then in your loop you were trying to do *nameptr[x] = names[x];, which means "take the names[x] object and replace the object that nameptr[x] points to with it". You were dereferencing pointer that has not yet been initialized, which leads to undefined behaviour

4 Comments

Awesome, thanks! I spent two hours with the class tutor trying to figure this out.
@Dorden: You're welcome. Check my answer now, I added the explanation of why your program "has stopped working". Hope it will help :)
@Lih0 Thanks, that does clear up some of my confusion with pointers. We're just getting into that stuff
@Dorden: Sure, we all were starting somehow :) Also a little side note: you don't need to return 0; in main in C++. It happens automatically.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.