-
gets() function
is that true:
Code:
#include <stdio.h>
#include <stdlib.h>
void _gets(char *str) {
char temp[1024];
str=temp;
}
void main() {
char *s;
_gets(s);
}
error:can not convert char* to char. what does this error mean?
and
void _gets(char *str) {
str=malloc(1024);
}
-
>is that true:
Is what true?
The code you have shown (use code tags please), is way wrong! What are you trying to do/understand. Please restate your question.
-
> void main()
That's way wrong.
I agree with hammer, what are you trying to do?
-
Well done for sorting out the tags :)
Now, this
>char *
is a pointer to a char. and this
>char
is a char (byte for you to store a character in).
Stepping through your code:
Code:
void _gets(char *str) {
char temp[1024];
str=temp;
}
This does nothing. The defintion of this function is:
- it takes a char * as a parameter (called str).
- it returns nothing.
Within it:
- It creates an array of 1024 bytes (for holding chars)
- It assignes str the address of the char array (temp)
Code:
void main() {
char *s;
_gets(s);
}
>void main()
no, use int main(void)
>char *s;
This creates a char * called s. Remember, this is only a pointer to a char. It does not create any space for you to store characters in.
>_gets(s);
This calls the function passing the pointer as a parameter.
Can you expand on what you are trying to do or understand, and someone can help you out better.
-
it seems to me that u r trying to code actionscript or something by using all the underscores in front of the data types
-
Code:
#include <stdio.h>
#include <stdlib.h>
/* Identifier clash, underscores are reserved,
** as are identifiers that start with str
*/
void _gets(char *str) {
char temp[1024];
/* temp is just that, temp. It won't exist when
** you return.
*/
str=temp;
}
/* Big no-no, your entire program is undefined
** starting here.
*/
void main() {
char *s;
_gets(s);
}
Let's rewrite this so that it's better. I'm assuming that you want to pass the function gets a char pointer which it will allocate memory for.
Code:
#include <stdio.h>
#include <stdlib.h>
static int gets_(char **st)
{
*st = malloc ( 1024 * sizeof **st );
if ( *st != NULL )
return EXIT_SUCCESS;
return EXIT_FAILURE;
}
int main ( void )
{
char *s = NULL;
if ( gets_(&s) == EXIT_SUCCESS )
free ( s );
return 0;
}
The names have been changed to protect the implementation, thorough testing of return values is performed so that bad thingsTM don't happen, and memory is freed at the end. This program is much better.
-Prelude