someGuy
someGuy

Reputation: 77

c ++ dynamic array and input string

I am new to pointers and I was wondering if someone can take a look at my code and tell me why I am getting an error " invalid conversion from Char to Char;

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main (int argc, char * const argv[]) {
    int stringlenght;
    string  input;

    cout << "Please enter a  string >";
    getline(cin,input);
    cout << "You entered: " << input  << endl << endl;

    stringlenght=input.length();
    cout << stringlenght;

    char *inputArray[stringlenght];
    for (int i=0; i < stringlenght; i ++) {
        inputArray[i]=input[i];
    }

    //system("pause");
}

Upvotes: 0

Views: 2472

Answers (3)

Filip
Filip

Reputation: 510

The problem with your example is that you have declared inputArray as an array of pointers to characters, and therefore inputArray[i] will be a pointer to a character.

What you are trying to do is assign the pointer at the i:th position in inputArray a character value.

What I think you would like to do is to declare inputArray as:

char *inputArray = new char[length];

... your loop ...

delete []inputArray;

This instead creates one pointer, and makes it point to a contigous area in memory where you can store characters, and therefore the type of inputArray[i] will be char instead of char *.

Upvotes: 1

small_duck
small_duck

Reputation: 3094

Your line char *inputArray[stringlenght]; defines an array of pointers. Aren't you trying just to define an array of char instead, that is, char inputArray[stringlenght];?

In this case, copying elements of your input into your inputArray would work, as you would be copying a char into a char.

Upvotes: 0

Jason
Jason

Reputation: 32490

This line here:

inputArray[i]=input[i];

Since inputArray is an array of char* and not char types, you can't assign a pointer the actual char type rvalue that is being returned by the operator[] method of the string type when used on the right-hand side of the assignment operator. The pointer-type needs to be assigned an actual address value. Try changing it to:

inputArray[i]=&input[i];

Keep in mind that if you do this, any operation on the string object could invalidate these stored pointers in the inputArray ...

Upvotes: 1

Related Questions