How can I write gets(???); Thank you.
void getStr(**temp){
gets(???);
}
void main(){
char *ch;
printf("Enter a string: \n");
getStr(&ch);
printf("main: %s\n", ch);
}
------ Output ------ Enter a string: abc main: abc
How can I write gets(???); Thank you.
void getStr(**temp){
gets(???);
}
void main(){
char *ch;
printf("Enter a string: \n");
getStr(&ch);
printf("main: %s\n", ch);
}
------ Output ------ Enter a string: abc main: abc
Copyright © 2021 Jogjafile Inc.
Never use the
gets
function. It is inherently unsafe, since there's no way to guard against overruns (the user entering more data than you're prepared to accept). In fact, it was removed from the language by the 2011 ISO C standard.You should probably use
fgets()
instead. It's a bit more complicated to use (for one thing, it leaves the'\n'
line terminator in the string), but it lets you specify the maximum number of characters to be read.Your
getStr
function probably doesn't need to take achar**
argument; achar*
would do, since it's not going to be modifying the pointer, just reading data into an array to which the pointer points.You'll need to allocate a
char
array to read the data into. You can either declare an array object:or use
malloc
to allocate the space.One more thing:
void main()
is incorrect. (Compilers are allowed to accept it, but there is no good reason to use it.) The correct definition isint main(void)
. If you have a book that's telling you to usevoid main()
, it was written by someone who doesn't know the C language very well, and it's likely to have more serious errors.Take a look at the comp.lang.c FAQ.