#include<stdio.h>
float func (float t, float y){
return y ;
}
int main (){
float t0,y0,t,y;
printf ("the value of t: ");
scanf ("%f",&t0);
printf ("the value of y: ");
scanf ("%f",&y0);
t=t0;
y=y0;
static int n=0;
// t[0]=t0;
// y[0]=y0;
for (n=0;n<=3;n++){
y[1]=y[0];
printf ("value of y %f %f \n",t,y);
}
return 0;
}
The error is:
Building prog.obj.
D:\master\c language\ch3\prog.c(166): warning #2117: Old-style function definition for 'main'.
D:\master\c language\ch3\prog.c(182): error #2144: Type error: pointer expected.
D:\master\c language\ch3\prog.c(182): error #2144: Type error: pointer expected.
*** Error code: 1 ***
You cannot array index something that is not an array, or a pointer into an array.
Your y and t floats are not pointers into arrays in your program.
You should make them float *y, *t into pointers so you can point them into array.
Change float t0,y0,t,y; to float t0,y0,*t,*y;
and
t=&t0; //assign address of t0 to t
y=&y0;
Change printf ("value of y %f %f \n",t,y); to
printf ("value of y %f %f \n",*t,*y); //note to dereference t and y here, to get their values
Here's a example of your program I fixed to work
The 'Old-style function definition for main()' message means that you've not given a prototype definition. The correct forms are:
int main(void) { ... }
int main(int argc, char **argv) { ... }
The version int main() is fine in C++, but not strictly a prototype in C, and hence gets the 'old-style' tag.
The other messages are more inscrutable; the line numbers do not correspond to the code you show. However, as Tony The Lion notes in his answer, the line
y[1] = y[0];
is erroneous since y is not an array. There is room to think that should be:
y = y0;
and you'd need a companion:
t = t0;
in order to have defined values printed in the printf() statement.
Even with these changes, the code does not make a lot of sense. However, given that you removed 150-odd lines, we can suppose that the missing code would make more sense.
There is no need to make n into a static variable; it is better not to do so.
Please make sure, in future, that your error messages correspond to the source code you post, not to some variant version of the code you post. The line numbers should not be as large as 166 or 182; they should be single digit numbers or small double digit numbers. But even more importantly, they should match the code!
Related
Okay this is actually a very simple code but since I am only starting to learn C, please be patient and help me out. I'll be putting my Questions as comments beside the code so that it easy to relate to which part of the code I have a doubt.
#include <stdio.h>
main()
{
int first_no, second_no;
float dec_no, output_no;
first_no = 75;
second_no = first_no/2;
dec_no = 35.3;
output_no = dec_no/3;
printf("First No:%d\n", first_no);
printf("Second No:%d\n", second_no);
printf("Third No:%d\n",output_no);
/*here I wanted to print only the integer part of the output_no */
}
The problem with this is that I had a book and it displayed the value for third no as 0.
And then in another program it says that compile time error is shown.
Second program:
#include <stdio.h>
void main()
{
int x = 5.3%2;
printf("Value of x is %d", x);
}
For this program, the book says that a compile time error will be shown. I fail to understand why that is the case. According to me the output should be 1.
If I were to use the following code instead of the previous code:
#include <stdio.h>
main()
{
int first_no, second_no;
float dec_no, output_no;
first_no = 75;
second_no = first_no/2;
dec_no = 35.3;
output_no = dec_no/3;
printf("First No:%d\n", first_no);
printf("Second No:%d\n", second_no);
printf("Third No:%d\n",dec_no);
}
What output should I expect? Do I still get a zero or some unpredictable output?
The problems with using just
printf("Third No:%d\n",output_no);
is that:
output_no gets converted to a double before being passed to printf.
When printf sees %d as the format specifier, it expects an int. When the object being passed is of type double, the behavior is undefined.
When you want to print a truncated integral value of a floating point number, you can do one of the following.
Create a temporary variable of the integral type and assign to it the floating point number.
int temp = output_no;
printf("Third No:%d\n", temp);
Explicitly cast the floating point number to an integral type.
printf("Third No:%d\n", (int)output_no);
printf("Third No:%d\n",dec_no);
What output should I expect? Do I
still get a zero or some unpredictable output?
As of the printf function is concerned,
When you try to print an integer value with format specifiers that are used for float (or) double and vice the versa the behaviour is unpredictable.
But it is possible to use %c to print the character equivalent of the integer value. Also using of %d to print ASCII value (integer representations) of character is acceptable.
Second program: For this program, the book says that a compile time
error will be shown.
According to C Reference manual
7.3.3 expression % expression
The binary % operator yields the remainder from the division of the first expression by the second. Both operands must be int or char, and
the result is int. In the current implementation, the remainder has
the same sign as the dividend.
Here in your case you are providing one value 5.3 so it is neither char nor int so that is why it generates compilation error.
If you still want to run that program you can do that by using fmod() function.
Try this code :
#include<stdio.h>
#include<math.h>
void main()
{
float x=5.3;
int c =2;
printf("Value of xremainer is %lf",fmod(x,c));
}
Compile it as :
$gcc test.c -lm
As I am new to programming, I was trying to write a simple code using functions which will give me the addition of three numbers. Here's the code!
/* Your includes go here */
#include <stdio.h>
int addThreeNumbers(int a, int b, int c)
{
int d;
d = a + b + c;
return(d);
/* Complete this function only
DO NOT write main function.
*/
}
int main()
{
int x, y, z, sum;
printf("Enter the three numbers: ");
scanf(" %d %d %d", &x, &y, &z);
sum = addThreeNumbers(x, y, z);
printf("The sum is %d", sum);
return 0;
}
And the error was as follows:
solution.c:30:5: error: redefinition of ‘main’
solution.c:15:9: note: previous definition of ‘main’ was here
You have another main function in the code somewhere. Post the complete code and I will take a closer look. But that is the only way you can receive this error
In modern C, empty argument parentheses mean that the type and number of arguments is unknown.
Although this segment runs fine with most compilers, yours might be picky. Try declaring main with zero arguments explicitly, like this:
int main(void) {
//code
}
Pretty sure this is one of the online coding sites' question. They put in the main function themselves by appending it to the code, you don't have to explicitly write it. Delete the main function you have written and check if that works out.
This is not homework, but my last assignment made it clear that I didn't clearly understand pointers when coding C.
Therefore, I tried to type a simple program using pointers just to invert an integer in a function, so I could figure out where the gap in my understanding is.
Apparently, I've arrived at it, but I still cannot figure out what I am doing wrong.
My source code is below.
#include <stdio.h>
float invert(int *num);
void main (void)
{
int num;
float a;
printf("enter an integer \n");
scanf("%i", &num);
printf("Number entered %i \n", num);
a=invert(&num);
printf("This is the invse from main %f \n", a);
}
float invert(int *num) /* function inverts integer */
{
float invse;
printf("num is %i \n\n", *num);
invse = 1/(float)num;
printf("invse is %f \n\n", invse);
return(invse);
}
My thinking was that I used the pointer to direct the computer to use the value stored at the address for num in the function invert(). The pointer appears in the variable declaration. I cast the value stored at that pointer as a float, so I could invert it, and store it in a local variable.
The problem appears to be in the local variable assignment. My compiler returns "invert.c:29:2: error: pointer value used where a floating point value was expected
invse = 1/(float)num;
^
Apparently my code indicates a pointer value for inverse, but I declared it as a float, which I find confusing.
Any help is appreciated. This will save me on completing my larger set of code for my assignment, which I did not post here.
Thanks.
Judging by the printf call inside invert
printf("num is %i \n\n", *num);
you already know that in order to access the value passed to invert for inversion you have to dereference num pointer: *num.
If so, then why aren't you dereferencing num when you perform the inversion itself?
invse = 1/(float)num;
I mean, if you are the one who wrote that printf, you should also realize that the actual inversion should be done as
invse = 1 / (float) *num;
or, alternatively, as
invse = 1.f / *num;
On top of being incorrect your original variant is illegal: you are not allowed to convert pointers to floating-point types in C, which is the reason for the error message.
P.S. From the bigger picture point of view, there's no real reason to pass that the number to invert by pointer. Passing the immediate value would make more sense
float invert(int num)
{
...
In that case you, of course, don't have to dereference anything inside invert.
I am having some trouble with pointers.
The gist of it is, I am trying to define pointers in one function and call that function in my main to use those pointers.
The exact instructions for my assignment are as follows:
Write two functions, one that reads three numbers from the keyboard
and one that prints some information about these three numbers.
Input Function
Write a function that has three integer pointer parameters, and that
asks the user to enter three whole numbers. The values entered at the
keyboard should be read into the addresses stored in the pointer
parameters.
Note: recall that scanf requires the address of a variable and that
pointers store addresses.
Printing Values
Write a second function called a2question2, with no return value and
no parameters. The function should declare three integer variables
and then use your input function to read values into these variables.
The function should then print the sum, the average, the product, and
the smallest and largest of these numbers.
Here is what I have so far:
int pntloc (int *x, int *y, int *z){
int a = 0;
int b = 0;
int c = 0;
printf("Please enter integer #1: ");
scanf ("%d", & a);
printf ("Please enter integer #2: ");
scanf ("%d", & b);
printf("Please enter integer #3: ");
scanf ("%d", & c);
*x = &a;
*y = &b;
*z = &c;
return *x, *y, *z;
}
// Fourth function
main (){
int x, y, z;
pntloc(x, y, z);
int sum = 0;
int average = 0;
int product = 0;
int smallest = 0;
int largest = 0;
printf ("%d", x);
}
However, after the program asks me for the three integers, it crashes without doing anything.
The first function works fine by its self (tested it by making it the main function without parameters and printed the pointer values) ie:
printf ("%d", *x);
So I guess the values are just not passing from one function to the next. I've tried various ways of writing the first and second function but nothing seems to work.
The best I got was getting the program not to crash but the printed value was nowhere to what I inputted before.
Any ideas how to do this?
Your program is probably crashing because of two errors:
1) You are returning the local address of the variables a, b and c:
*x = &a; // This line says follow the 'x' pointer, and set the value there to
// the address of 'a'
Since a is defined locally (i.e. inside the function), that address is invalid once the function returns.
What you probably meant is:
*x = a; // Follow the 'x' pointer, and set the value there to the value of 'a'
2) You're not passing pointers to pntloc() (your compiler should be warning you about this one)
int x, y, z;
pntloc(x, y, z); // The passes the VALUES of x, y and z
You probably meant:
pntloc(&x, &y, &z); // Pass the ADDRESSES of x, y and z
Some other improvements that aren't causing your crash:
You can massively shorten pntloc() by not using the local variables:
void pntloc (int *x, int *y, int *z){
printf("Please enter integer #1: ");
scanf ("%d", x);
printf ("Please enter integer #2: ");
scanf ("%d", y);
printf("Please enter integer #3: ");
scanf ("%d", z);
}
Note that the & has been removed inside the scanf() call. You asked about it in comments, so here's a bit more explanation: &x says "the address of x", but when you have a pointer, you already have an address. A quick example:
int a; // 'a' is an integer variable
int *b = &a; // 'b' is a pointer to the integer variable 'a'
scanf("%d",&a); // This statement reads an integer into 'a'.
// We pass it the address of 'a', which is written &a
scanf("%d",b); // This statement also reads an integer into 'a'.
// We pass it the address of 'a', which is stored
// in the pointer 'b'.
Since we have pointers passed in to the function:
void pntloc (int *x, int *y, int *z){ // Three pointers to ints
we can pass them straight in to scanf(), and don't need to (and shouldn't) use & when we do.
Note that I also removed the return statement:
return *x, *y, *z;
I don't think this return statement is doing what you think it is. Remember that C only allows one return value from a function.
But why does it compile, you ask? Well, here's what's happening - but feel free to ignore this bit if it is confusing: The comma operator evaluates left to right, discarding the left hand result as it goes. So, your return statement is equivalent to:
*x;
*y;
return *z;
The comma operator is useful when the left hand statement has a side effect, and you want to write everything on one line. In my opinion, it makes code much harder to read, but there are one or two situations where it makes things cleaner. For a beginner, I recommend the following rule: Only use commas inside the round brackets of functions.
Since you weren't using the return value from the function when you called it:
pntloc(&x,&y,&z);
I removed the return entirely, and set the return type to void.
*x = &a;
*y = &b;
*z = &c;
Will cause mayhem and death! a b and c are local variables, so you are setting the contents of x y and z to addresses that will be invalid once you return from the function where a b and c are defined.
Perhaps you mean:
*x = a;
*y = b;
*z = c;
in main(),
pntloc(&x, &y, &z);
and
*x = a;
...
printf ("%d", x);
while you pass the *x as a parameter in pntloc(), you can't change *x 's value after calling the function.
and pntloc() don't need to return them, returning 0 or 1 is enough.
today,I write some code to test unsigned int.
#include <stdio.h>
int sum_element(float ele[], unsigned int len);
int main(void){
float ele[] = {1.1,2.2,3.3};
float sum = sum_element(ele,3);
printf("sum is %f\n",sum);
return 0;
}
int sum_element(float ele[], unsigned int len){
int sum=0.0; //mistake,should be : float sum = 0.0
int i=0;
for(i=0;i<= len-1;i++){
printf("sum=%f, i=%d\n",sum,i);
sum += ele[i];
}
return sum;
}
in this example, i have a mistake, the type of variable sum, should be float, but i write int, the compile command:
gcc test.c -o test
and i run this code
./test
the output of the function sum_element is:
sum=0.000000, i=1
sum=0.000000, i=1
sum=0.000000, i=1
and then i found the mistakes, and i change the type of sum to float, then compiled again,
and when i run it, the output is :
sum=0.000000, i=0
sum=1.100000, i=1
sum=3.300000, i=2
this time, the output like normal,but in first output, why the variable of i is always the same value of 1, can someone tell me?
Nothing to see. You invoked undefined behavior by passing the wrong type to printf, so all output of the program is meaningless. The %f format specifier requires an argument of type double (by the way, float would automatically promote to double in this context, so float would be okay too), but you passed it an argument of type int.
You have to understand how va_arg work. Printf is a function that take a undefined number of arguments. The problem is that those arguments are not typed.
When you specify int, double, ect... the compiler assign differente number of bytes (in a specific order) depending on the arguments. So when you call a function that has type argument, the function know how it should read those bytes.
Here it cannot know since it isn't type. So the printf function is going to believe what you give it. If you ask for example for a 4 bytes when you real value is 8 bytes, the function will read the first 4 bytes believing it the value you ask for. But then the next value you try to match will start with the next 4 bytes. Wich will give you garbage.
You can try to do 2 printf, and you will see that the value of i is actually the good one. Only the way to read it was wrong.
int sum_element(float ele[], unsigned int len){
int sum=0.0; //mistake,should be : float sum = 0.0
int i=0;
for(i=0;i<= len-1;i++){
printf("sum=%f\n",sum);
printf("i=%d\n",i);
}
return sum;
}
Hope this can help.
EDIT:
Maybe a example is easier to understand. Try this function:
int sum_element(float ele[], unsigned int len){
int sum=24222.55455555; //mistake,should be : float sum = 0.0
char c = 0 ;
for(i=0;i<= len-1;i++){
printf("sum=%f, n= %d n2 = %d\n",sum,i,c);
}
return sum;
}
You should get a interesting value for n2.
I think the answer is that in the first case, the value being printed is not that of i at all. Two parameters are passed to printf which then reads two off. Those passed in are two ints, and then a double and and int are read off. Because the double is read off the stack first, when the int is read it is not from where the value of i was passed, hence the bogus value. Most likely the double covers enough of the stack to include both the passed ints.
Of course, results may vary, being undefined.