1

I've been trying everything under the sun to do the simple following:

1) Receive an input string from stdin.

2) Convert it to a char pointer so I can pass to a tabling/palindrome finding function.

I'm confident in the latter part of step 2, but it's the type agreement I can't hack. Below is my main body in question. The prototype of the palin function is int palin(char *str).

int main()
{
    string input;
    cin >> input;
    char seq[] = input.c_str(); //Error here, invalid initialization?
    int len = strlen(seq);
    int result = palin(seq);
    cout << result;
    getchar();
    return 0;
}

Any ideas? c_str() conversion also presents a problem as it expects a constant pointer char, but my char pointer will change.

Uyghur Lives Matter
  • 18,820
  • 42
  • 108
  • 144
Rome_Leader
  • 2,518
  • 9
  • 42
  • 73
  • char X[] must have size known at compile time. Also c_str returns `const char*` not `char*` – Creris Oct 18 '14 at 14:35
  • If `palin()` only reads the string then you can simply say `const char *seq = input.c_str();` (and declare `palin(const char*).`) Otherwise you'll have to strcpy into a new char array. – Peter - Reinstate Monica Oct 18 '14 at 14:36
  • I've seen the above proposed duplicate, but const char won't do for me. It needs to be mutable. – Rome_Leader Oct 18 '14 at 14:38
  • `&input[0]` will return you pointer to first element, and since C++11 standard, string is required to be contiguous, but I dont think it is required to be null-terminated(even tho afaik all implementations do this) – Creris Oct 18 '14 at 14:42
  • So why have the string at all? You could read right into the buffer with scanf. – Adrian May Oct 18 '14 at 14:43
  • also there is no need to have nonconstant pointer to character, because in no way, shape or form are you required to modify state of C strings when examining them(Is it palindrome?) – Creris Oct 18 '14 at 14:58

2 Answers2

2

If indeed it needs to be mutable you need to copy the string into a mutable buffer that is passed to palin, something like:

int main()
{
  string input;
  cin >> input;
  char seq[input.length() + 1];
  memcpy(seq, input.c_str(), sizeof seq);
  int result = palin(seq);
  cout << result;
}
Bishop
  • 188
  • 4
0

You can try strdup

char *c = strdup(str.c_str());

// Do stuff with c

// Make sure to free c when you are done.    
free(c)
rlrr
  • 26
  • 4