How can I use gets() in a function to assign string in char *ch?

112 Views Asked by At

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

1

There are 1 best solutions below

0
On

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 a char** argument; a char* 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:

char line[200]; // for example

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 is int main(void). If you have a book that's telling you to use void 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.