I really have no idea why there's a 'warning' in this code..Code:#include <stdio.h>
int main()
{
char address;
printf("Enter your address: ");
gets(address);
printf("Your address is %s", address);
return 0;}
Any help plz..?
Printable View
I really have no idea why there's a 'warning' in this code..Code:#include <stdio.h>
int main()
{
char address;
printf("Enter your address: ");
gets(address);
printf("Your address is %s", address);
return 0;}
Any help plz..?
The mostly like reason is that gets() expects to receive a pointer which is the address of the first element of an array. It does not expect what you're doing - supplying the value of a single char.
The same goes for the %s format specifier for printf.()
If your compiler is fairly modern, it may also complain about using gets() AT ALL, since gets() was REMOVED from the latest C standard. This is because gets() is dangerous and there is no way for a programmer to make its usage safe. Look up the fgets() function for an alternative.
I'm pretty new to programming and a book said never use gets() in real life, but for an example use it... I understand that, but my compiler (gcc) gave me a segmentation fault when I ran it. So I had to use scanf(). Any ideas on how to fix that?
> I understand that, but my compiler (gcc) gave me a segmentation fault when I ran it
Well that's what you get for ignoring warnings, and passing garbage into functions.
In your code, address is a single character, when what you need is an array. Make address a char array of size 50 (for example), and everything should start to work.
I will add also that the use gets is highly not recommended. Use fgets instead. Information on this is everywhere, even in Wikipedia.
Okay so...
You have declared "address" as a char.
This reserves enough space for one letter
gets() tries to put more than one letter at the variable "address": Your computer sees your program trying to modify memory that it doesn't have permission to modify, so it throws a segfault.Code:address = 'A';
Here is a tutorial on how to reserve more than just one char
Arrays in C - Cprogramming.com
Here is a tutorial on strings (which is what you are after) which has an fgets() example.
C Strings - Cprogramming.com
A string (in the C language) is an array of chars where the final character is a Nul '\0' character.
(Note that this is not NULL with 2 L's, as NULL is a pointer which points to nothing FAQ > NULL, 0, \0 and nul? - Cprogramming.com)
The string "Hello" would be stored in an array as,, and the array it is stored would have to have a size of at least 6.Code:{'H', 'e', 'l', 'l', 'o', '\0'}