-1

I have a string "prompt" that holds a string of characters. The user must be able to change the prompt with user input, which I've collected and separated (using whitespace as a delimiter) into an array of char strings (tokens).

For example, assume:

char **tokens[2] = {"setprompt", "newprompt"};
char *prompt = "oldprompt";

if(strcmp(tokens[0], "setprompt") == 0)
{
strcpy(prompt, tokens[1]);
}

The strcmp() function works perfectly fine, however when it reaches strcpy(), the element in tokens[1] (which is the string "newprompt") isn't copied into the string prompt. This is my problem.

I've tried troubleshooting, in addition to using strncpy() instead but I think there's an issue somewhere with my declarations of each variable/pointer. Any assistance or ideas would be great.

Note: in my actual program, the tokens array doesn't have a definitive size of 2. This example is modified for simplicity. Thanks!

Jacob Zwiers
  • 1,092
  • 1
  • 13
  • 33

1 Answers1

3

Your issue is this line:

char *prompt = "oldprompt";

It points to constant memory and cannot be modified (the way it is defined). Consider leaving it read-only and creating your own buffer instead for copying and modifying Something like:

#define MAX_STRING_SIZE 255

char *tokens[2] = {"setprompt", "newprompt"};
char *prompt = "oldprompt";
char myBuffer[MAX_STRING_SIZE];

strcpy(myBuffer, prompt );

if(strcmp(tokens[0], "setprompt") == 0)
{
    strcpy(myBuffer, tokens[1]);
}
Michael Dorgan
  • 12,453
  • 3
  • 31
  • 61
  • Lots of ways to skin this cat. I went with something very simple and easy to understand to start. I'm surprised that he wasn't getting some kind of run-time error about the copy causing a crash. – Michael Dorgan Nov 15 '17 at 01:20
  • `char **tokens[2] = {"setprompt", "newprompt"};` See [comment](https://stackoverflow.com/questions/47297861/in-c-im-unable-to-copy-a-single-element-of-an-array-of-character-strings-to-an#comment81548105_47297861). This is poor code. – chux - Reinstate Monica Nov 15 '17 at 02:18
  • 1
    yeah, nice catch. – Michael Dorgan Nov 15 '17 at 02:35
  • Difference between *array of pointer to pointer to char [2]* and *array of pointer to char [2]*. – David C. Rankin Nov 15 '17 at 02:39