I am using Linux.
I am trying to write a program in c that will print a string backward.
Here is my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main (){
char string[100];
printf ("Enter string:\n");
gets (string);
int length = strlen (string)-1;
for (length = length; length>=0; length--){
puts (string[length]);
}
}
And here is the error:
a.c:10: warning: passing argument 1 of ‘puts’ makes pointer from integer without a cast
/usr/include/stdio.h:668: note: expected ‘const char *’ but argument is of type ‘char’
/tmp/cc5rpeG7.o: In function `main':
a.c:(.text+0x29): warning: the `gets' function is dangerous and should not be used.
What should I do?
First:
NEVER NEVER NEVER NEVER NEVER use
gets(); it will introduce a point of failure in your code. There’s no way to tellgets()how big the target buffer is, so if you pass a buffer sized to hold 10 characters and there’s 100 characters in the input stream,gets()will happily store those extra 90 characters in the memory beyond the end of your buffer, potentially clobbering something important. Buffer overruns are an easy malware exploit; the Morris worm specifically exploited agets()call in sendmail.Use
fgets()instead; it allows you to specify the maximum number of characters to read from the input stream. However, unlikegets(),fgets()will save the terminating newline character to the buffer if there’s room for it, so you have to account for that:Now that’s out of the way…
Your error is coming from the fact that
puts()expects an argument of typechar *, but you’re passing an argument of typechar, hence the “pointer from integer without cast” message (charis an integral type). To write a single character to stdout, useputchar()orfputc().