0

Can I do code such:

char *p;
p = User_input;

Is it possible to assign a string to p at runtime?

1
  • 2
    You can make p point to an existing string by setting p equal to a pointer to the first character of that string. But before you can get user input, you'll likely need to allocate some memory to get the input into. Commented Oct 8, 2011 at 13:40

4 Answers 4

1

Sure you can, but there is no string in c, I think you mean char *, like

char *user_input = malloc(128);
scanf("%s", userinput);
p = user_input;
1

You have to allocate the memory with malloc. Then you can use strcpy to assign a string to the allocated memory.

1

Of course you can. Note that this assignment only copies the pointer (the address) to the new variable. It does not copy the string itself.

You have other options if this is not what you ment:

char buf[1000];

strcpy(buf, User_input);

or

char *p;

p = strdup(User_input);
1

To avoid dangerous buffer overflows with scanf. Use fgets for reading whole line or scanf with a limit specififier "%100s" for example.

char buffer[128];
scanf("%127s", buffer);
char* my_input = strdup(buffer);

Not the answer you're looking for? Browse other questions tagged or ask your own question.