0

Can you take input from a user for a pointer [solved]

Can you take in input from a user and directly assign it to a pointer without an intermediate variable. I'm actually talking about char pointers. So is there any way I can declare a pointer char *name; And directly assign user input to it. In the code attached, using scanf did not work. I had to use an intermediate variable to store the input them point the pointer to the variable. So is there any way of directly assigning user input to the variable https://code.sololearn.com/cu0RawEwrT4s/?ref=app

25th Feb 2021, 8:24 PM
Sekiro
Sekiro - avatar
3 Respostas
+ 6
You can, if you had the pointer properly setup using dynamic memory allocation. A pointer needs to point to a writable memory block when it is to be used to receive input. #include <stdio.h> #include <stdlib.h> int main() { char* name = (char*)malloc(101 * sizeof(char)); if(!name) { puts("Cannot allocate memory"); return -1; } scanf("%100[^\n]s",name); puts(name); free(name); return 0; }
25th Feb 2021, 8:45 PM
Ipang
+ 3
No problem bro 👌
25th Feb 2021, 11:48 PM
Ipang
+ 1
Ipang Thanks man
25th Feb 2021, 9:12 PM
Sekiro
Sekiro - avatar