Reputation: 7857
I've undertaken learning c with the aid of the k & r book. Pretty exciting but I've run into trouble early on and I'm not sure how to fix the problem.
I'm trying out some really simple sample code and I'm getting the following error. I don't understand why because the code is straight out of the book.
main.c:11: warning: passing argument 2 of ‘sprintf’ makes pointer from integer without a cast
#include <stdio.h>
/* copy input to output; 1st version */
main() {
int i;
int power(int base, int n);
for (i = 0; i < 10; i++) {
sprintf("%d %d %d\n", i ,power(2, i), power(-3, i));
return 0;
}
}
int power(int base, int n) {
int i;
int p;
p = 1;
for (i = 1; i <= n; ++i)
p = p * base;
return p;
}
I'd appreciate a nudge to get me going on my way again.
Upvotes: 6
Views: 19250
Reputation: 156
for everybody who dont knows abouwt the loop with return there is a differance between:
for (i = 1; i <= n; ++i)
p = p * base; //inside
return p; //outside because no brackets {}
and:
for (i = 1; i <= n; ++i){
p = p * base; //inside
return p;} //inside because brackets {}
if you don't use brackets in a loop or if statement, only the direct next line will be executed. this return is outside the loop
Upvotes: 1
Reputation: 17761
this is just a compiler warning, but the process should have been completed succesfully if you didnt get any error messages... you could get around the warning by adding an explicit cast to line 11.. check for "type casting c" on google ;)
Upvotes: 0
Reputation: 9942
The first argument of sprintf()
is the buffer you are supposed to be printing to. The second is the format string.
(Also consider using snprintf()
-- it's much easier to write safe code that doesn't overrun the buffer.)
Upvotes: 0
Reputation: 67879
sprintf()
expects a string as first and second arguments.
The first one designates the string where you want to store the result and the second one is the format string.
You may want to use printf()
instead of sprintf()
.
Upvotes: 0
Reputation: 4465
From man sprintf
:
int sprintf(char *str, const char *format, ...);
The first argument to sprintf is the string you have allocated.
If you want to print to the standard output (usually the terminal in which you run the program), use printf
instead.
Upvotes: 3
Reputation: 80031
sprintf
is for creating a string based on some formatting. It looks like you want output, so you want to use printf
.
Also, return 0;
should not be be enclosed in your for
loop. It would result in termination of the program after one iteration.
Upvotes: 6