Defining Array Of Pointers to String

I am begining computer science student and I am trying to learn how to create an array of pointers to point to an array of strings. I plan on sorting the pointers later but right now I get a syntax error just trying to assign one string address to one pointer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>
using namespace std;


int main() {
   string x[10];
   char * charPtr[50];
 
   x[7] = "String Test";
   charPtr[7] = &x[7];

   cout << "x ==>" << x[7] << endl;
   cout << "intptr ==>" << charPtr[7] << endl;
   cout << "intptr ==>" << *charPtr[7] << endl;
    


This is the error. I am using BloodDev IDE
11 C:\Dev-Cpp\PtrTest.cpp cannot convert `std::string*' to `char*' in assignment
You can't assign strings. Use strcpy function
 
strcpy( charPtr[7] , x[7].c_str() );
a 'string' is not a 'char'. If you have a char*, then it must point to a char, not a string. If you want to point to a string, use 'string*'

ie:

1
2
3
4
string x[10];
string* ptrs[50];

ptrs[7] = &x[7];  // works just fine 


EDIT:

You can't assign strings. Use strcpy function


^ don't do that unless charPtr actually points to something (which, in this case, it doesn't!)

heap corruption, program crash, etc, etc.

char* is just a pointer, it is not a string.
Last edited on
Disch, so are you saying that this is dangerous, x[7] = "String Test"; ?? I did compile and run this and it "seemed to work". I am worried that that it works ok now but later it will cause a run time error.


1
2
3
4
5
6
int main() {
   string x[10];
   string * charPtr[50];
 
   x[7] = "String Test";
   charPtr[7] = &x[7];
Your code is fine. You're not doing anything wrong.

Using strcpy() to copy a string to a char pointer that doesn't point to anything is not fine -- but this is not what you're doing, so don't worry about it.
Topic archived. No new replies allowed.