Reputation: 49
I am embarrassed asking such a question, but it has been years since I coded in C, and frankly it is taking a lot longer for the language to come back to me than I anticipated.
I am getting the following warning "format %s expects argument of type char *, but argument 2 has type int" in my code, shown below.
#include <stdio.h>
#define MAXLINE 1000
int getNextLine(char line[], int maxline);
void reverse(char line[], int len);
main()
{
int len;
int max;
char line[MAXLINE];
char longest[MAXLINE];
max = 0;
while ((len = getNextLine(line, MAXLINE)) > 0)
{
reverse(line, len);
}
return 0;
}
void reverse(char line[], int len)
{
if (len == 0)
return;
else
{
printf("%s",line[len-1]);
line[len-1] = '\0';
//reverse(s,len-1);
}
return;
}
int getNextLine(char s[], int lim)
{
int c, i;
for (i=0; i < lim-1 && (c=getchar()) != EOF && c!='\n'; i++)
s[i] = c;
if (c == '\n')
{
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
What I don't understand, is that it seems to be something with the parameters? When I strip reverse() down such that it takes 0 arguments and just prints out a line of gibberish, the program compiles without warning. Hence, my suspicion that the parameters are my problem. What is even more confusing, as that the function getNextLine() has the same parameter count and types, yet this function has no issues?
Thanks, Chris
Upvotes: 1
Views: 356
Reputation: 42133
Function reverse
takes the argument line
of type char[]
, i.e. array of char
s, i.e. string, so:
printf("%s", line[len-1]);
should either be (in case you want to print a single character):
printf("%c", line[len-1]);
or (in case you want to print null-terminated string):
printf("%s", line);
"the function getNextLine
has the same parameter count and types, yet this function has no issues?"
~> The error your compiler gives you is related to printf
, which is not used in the other function.
"it has been years since I coded in C"
~> Side note: Your code reminds the old ANSI C. It's very long time since the last time that it was a must to declare all variables at the beginning of the function.
Upvotes: 2
Reputation: 2594
One character has an int type in C. line[len-1] then translates to int and that's what the compiler is complaining about. Seeing %s qualifier printf function expects a pointer to the beginning of a string. It will then follow to print characters starting from pointed address until it encounters \0. If you want to print one character use %c and provide an int (aka char).
Upvotes: 1
Reputation: 1667
it's because line[len-1]
is not a string .line
is a string so try printf("%s" , line)
or printf("%c" , line[len-1])
instead
Upvotes: 2