I have the following C code in a program:
printf("Test before print_foo()");
void print_foo(char board[ROW][COL]);
printf("Test after print_foo()");
where print_foo printf's the passed in 2-D character array with proper .c and .h files imported.
Console output is only the two printf statements.
Debugging, the run-time never even steps into print_foo.
Any ideas?
That void prefix is making the middle line into a declaration of function print_foo (and the char within the parentheses means it would be invalid syntax otherwise). To just call print_foo, change the middle line to print_foo(board); (if board is how you named that 2-D character array).
That looks like a function declaration to me - that's why your foo-nction is not being called.
Your middle line is just a function declaration, not a function call.
If you didn't declare the prototype previously then you have to write this :
printf("Test before print_foo()");
void print_foo(char board[ROW][COL]);
print_foo(board);
printf("Test after print_foo()");
In short you have to define/declare print_foo before invoking,or your compiler will flag an error !!
void print_foo(char board[ROW][COL]);
is not a function call. It's a declaration.
You probably want
print_foo(board);
Related
I am getting a strange error that's saying that my variables are not declared even though I have declared them in main. Am I missing something?
Error 4 error C2065: 'destination' : undeclared identifier c:\users\owner\documents\visual studio 2012\projects\project36\project36\source.c 26 1 Project36
I am programming in C.
variable declaration:
char sourcePiece;
char destination;
function call:
askForMove(sourcePiece, destination);
function def:
void askForMove(char sourcePiece, char destination) {
char sourcePiece;
char destination;
printf("\nEnter your desired move. First enter the starting position, followed by the ending position in letters: ");
scanf(" %c %c", &sourcePiece, &destination);
}
prototype:
void askForMove(char, char );
As it has been noted by some commenters, one of the problems is that you cannot have a local variable and a formal parameter with the same name. I suggest that you remove the declarations of the local variables, because it's the parameters that you want to use in your function, not them.
The full version of the code and the latest screenshot with the errors that you posted indicate that the compiler complains about the local variable declarations made in main function. The compiler complains because the variable declarations are interleaved with statements inside main, which was not supported by "classic" C language (C89/90). In order to compile this code you need a C99 (or later) compiler.
The code is easy to fix for a pre-C99 compiler - just move all local variable declarations to the beginning of the enclosing block (i.e. to the beginning of main in your case).
You Should Know that
Formal parameters, are treated as local variables within a function.
So Here You are duplicating them and it is causing error.
void askForMove(char sourcePiece, char destination) {
char sourcePiece; //Redeclaring already present in formal parameter.
char destination; //Redeclaring already present in formal parameter.
printf("\nEnter your desired move. First enter the starting position, followed by the ending position in letters: ");
scanf(" %c %c", &sourcePiece, &destination);
}
Remove Them
void askForMove(char sourcePiece, char destination) {
printf("\nEnter your desired move. First enter the starting position, followed by the ending position in letters: ");
scanf(" %c %c", &sourcePiece, &destination);
}
Also Note your question is not a good example of how one should write , Always Post Minimal, Complete, and Verifiable example.
Update
What AnT is saying make sense , see this C89, Mixing Variable Declarations and Code
I'm not sure what you intended to achieve in your program but you have a duplication in your variable names. Don't use the same name for the function argument and the local variable.
I want to use a macro defined in different header files with the same name and different implementations.
I have two header files h1.h and h2.h. In the first header file I defined:
#define PRINT printf(" hi , macro 1\n");
and in the second header file
#define PRINT printf(" hi , macro 2\n");
in main() when I try to use PRINT it is printed depending on the order of inclusion.
I found some similar problems and they used a wrapper, by including the first header file then defining an inline method:
inline void print1() {
PRINT();
}
and then undefining PRINT and including the second header file. In main() when I call print1() and PRINT I got the output from them both.
My missing point is how after we have undefined the PRINT from the first header file we are still able to have it - in other words what happens when we call it inside the inline function? Did the compiler copy the value of PRINT and assign it to the function and save the function in some way?
If I understand correctly, something like this is happening:
#include "h1.h" // defines PRINT: printf(" hi , macro 1\n");
inline void print1(){
PRINT();
}
#undef PRINT
#include "h2.h" // defines PRINT: printf(" hi , macro 2\n");
Nothing weird happens though. The pre-processor substitues PRINT inside the inline function before it is un-defined. So in the resulting code (you can see this when you compile with the -E flag for GCC), it becomes this:
// contents of h1.h...
inline void print1(){
printf(" hi , macro 1\n");
}
// contents of h2.h...
#defined macros are only kept for the duration of the pre-processing, and are substituted as the pre-processor goes along. Similar to variables in normal programming, if you re-assign it the pre-processor will just use the new value for following occurrences.
It works because during compilation the pre-processor reaches the PRINT() call in print1, evaluates the macro, and replace it with its current value. Then, if I understand correctly, later (in the next lines) you redefine or undefine PRINT (be it by including another header), then any further reference to it will make the pre-processor replace it with its current value again (which is now different), therefore you get 2 distinct behaviours calling the "same" macro.
The book's I'm using to learn C explains something called "prototypes" which I couldn't understand properly. In the book, the following sample code explains these "prototypes". What does this mean here? What are the "prototypes"?
//* two_func.c -- a program using two functions in one file */
#include <stdio.h>
void butler(void);
int main(void)
{
printf("I will summon the butler function.\n");
butler();
printf("Yes! bring me some tea and writable DVD's.\n");
getchar();
return 0;
}
void butler(void) /*start of function definition*/
{
printf("You rang,sir.\n");
}
Please explain in simple terms.
Function prototypes (also called "forward declarations") declare functions without providing the "body" right away. You write prototypes in addition to the functions themselves in order to tell the compiler about the function that you define elsewhere:
Your prototype void butler(void); does all of the following things:
It tells the compiler that function butler exists,
It tells that butler takes no parameters, and
It tells that butler does not return anything.
Prototypes are useful because they help you hide implementation details of the function. You put your prototypes in a header file of your library, and place the implementation in a C file. This lets the code that depends on your library to be compiled separately from your code - a very important thing.
In this context prototype is a more generic term for what in C would be called a function declaration, i.e.:
void butler(void);
You may also find it called function signature. Both terms actually refer more to how butler() is defined from a conceptual point of view, as a function that doesn't take any argument and doesn't return a value, rather that to the fact that its declaration is enough for you to use it in your source code.
This is the prototype:
void butler(void);
Basically it defines butler as a function that takes no parameters and has no return value. It allows the compiler to continue onwards, even though the butler function has not yet really been defined. Note that the prototype doesn't contain any actual code. It simply defines what the butler function looks like from the outside. The actual code can come later in the file.
If your code had been
#include <stdio.h>
int main(void) {
butler(); // note this line
}
void butler() { return; }
The compiler would have stopped at the note this line section, complaining that butler() doesn't exist. It will not scan the whole file first for functions, it'll simply stop at the first undefined function call it encounters.
Prototype comprises the return type of a function, its name and the order of different types of parameters that you pass it.
If you write the function definition before calling the function, then a prototype is not necessary. But, as is the case in your example, the function butler() is called BEFORE its definition and so, a prototype is necessary to tell the compiler that such a function exists which will have so and so return type and parameters.
Otherwise, writing the function definition after calling the function will result in error.
void butler(void);
Is Called prototype or declaration of function.
And below is the function definition.
void butler(void) /*function definition */
{
printf("You rang,sir.\n");
}
A few years back i was working with Turbo C compiler and the following code worked fine on it.
#include<stdio.h>
void main()
{
int a=2,b=3;
swap(a,b);
printf("%d\n%d\n",a,b);
}
swap(int *x,int *y)
{
int t;
//x=malloc(2);
//y=malloc(2);
t=*x;
*x=*y;
*y=t;
printf("%d\n%d\n",x,y);
}
Now i am working on cygwin and if i run this code i get an error Segmentation fault(core dumped)
If i uncomment the malloc statements i get the output
536937064
536937080
2
3
Are first two lines of output some garbage values? What exactly is happening here and how can i get the correct output?
Here is the corrected version of your program, which will execute correctly.
There are a number of things going wrong in the sample you posted:
Incorrect Argument type being passed:
swap(a,b);
should be :
swap(&a,&b);
Your function expects pointer to the integers to be modified, You are not doing so.
Incorrect Format specifiers for printf:
printf("%d\n%d\n",x,y);
should be:
printf("%d\n%d\n",*x,*y);
printf is not type safe and you need to ensure you use proper format specifiers while using it. Using incorrect format specifiers results in Undefined Behavior.
The next two are good practices if not errors and you should follow them.
Incorrect return type of main():
As per the Standard a program should return int,
void main()
should be
int main()
Also, add return a value return 0;at the end of main.
Function Declaration:
You should declare the function swap() correctly before main:
void swap(int *x,int *y);
Providing a function declaration before the place where you use it in code, gives the compiler a opportunity to match the parameters and report incorrect types being passed.
Further using malloc as you have would not acheive what you are trying to achieve, You do not need to use malloc here at all and One should always avoid using it as much as possible.
Also, You should pick up a good book and learn the basics.
Nothing here is actually correct.
The parameters to swap are the literal addresses 2 and 3. You can &a and &b in the call.
printf in swap is printing the pointer addresses, so the output is "expected".
If you were using malloc (why?), you are only allocating 2 bytes. An int is generally 4 , but please use sizeof.
You are passing values of the variables and using pointers to receive it.
`swap(a,b) `
should be swap(&a,&b)
because you must pass the address of the variables, not the variable itself. Read Call by reference in C.
int main()
{
int j=97;
char arr[4]="Abc";
printf(arr,j);
getch();
return 0;
}
this code gives me a stack overflow error why?
But if instead of printf(arr,j) we use printf(arr) then it prints Abc.
please tell me how printf works , means 1st argument is const char* type so how arr is
treated by compiler.
sorry! above code is right it doesn't give any error,I write this by mistake. but below code give stack overflow error.
#include <stdio.h>
int main()
{
int i, a[i];
getch();
return 0;
}
since variable i take any garbage value so that will be the size of the array
so why this code give this error when i use DEV C++ and if I use TURBO C++ 3.0 then
error:constant expression required displayed. if size of array can't be variable then when
we take size of array through user input.no error is displayed. but why in this case.
please tell me how printf works
First of all, pass only non-user supplied or validated strings to the first argument of printf()!
printf() accepts a variable number of arguments after the required const char* argument (because printf() is what's called a variadic function). The first const char* argument is where you pass a format string so that printf() knows how to display the rest of your arguments.
If the arr character array contains user-inputted values, then it may cause a segfault if the string happens to contain those formatting placeholders, so the format string should always be a hard-coded constant (or validated) string. Your code sample is simple enough to see that it's really a constant, but it's still good practice to get used to printf("%s", arr) to display strings instead of passing them directly to the first argument (unless you absolutely have to of course).
That being said, you use the formatting placeholders (those that start with %) to format the output. If you want to display:
Abc 97
Then your call to printf() should be:
printf("%s %d", arr, j);
The %s tells printf() that the second argument should be interpreted as a pointer to a null-terminated string. The %d tells printf() that the third argument should be interpreted as a signed decimal.
this code gives me a stack overflow error why?
See AndreyT's answer.
I see that now the OP changed the description of the behavior to something totally different, so my explanation no longer applies to his code. Nevertheless, the points I made about variadic functions still stand.
This code results in stack invalidation (or something similar) because you failed to declare function printf. printf is a so called variadic function, it takes variable number of arguments. In C language it has [almost] always been mandatory to declare variadic functions before calling them. The practical reason for this requirement is that variadic functions might (and often will) require some special approach for argument passing. It is often called a calling convention. If you forget to declare a variadic function before calling it, a pre-C99 compiler will assume that it is an ordinary non-variadic function and call it as an ordinary function. I.e. it will use a wrong calling convention, which in turn will lead to stack invalidation. This all depends on the implementation: some might even appear to "work" fine, some will crash. But in any case you absolutely have to declare variadic functions before calling them.
In this case you should include <stdio.h> before calling printf. Header file <stdio.h> is a standard header that contains the declaration of printf. You forgot to do it; hence the error (most likely). There's no way to be 100% sure, since it depends on the implementation.
Otherwise, your code is valid. The code is weird, since you are passing j to printf without supplying a format specifier for it, but it is not an error - printf simply ignores extra variadic arguments. Your code should print Abc in any case. Add #include <stdio.h> at the beginning of your code, and it should work fine, assuming it does what you wanted it to do.
Again, this code
#include <stdio.h>
int main()
{
int j=97;
char arr[4]="Abc";
printf(arr,j);
return 0;
}
is a strange, but perfectly valid C program with a perfectly defined output (adding \n at the end of the output would be a good idea though).
In your line int i, a[i]; in the corrected sample of broken code, a is a variable-length array of i elements, but i is uninitialized. Thus your program has undefined behavior.
You see strings in C language are treated as char* and printf function can print a string directly. For printing strings using this function you should use such code:
printf("%s", arr);
%s tells the function that the first variable will be char*.
If you want to print both arr and j you should define the format first:
printf("%s%d", arr, j);
%d tells the function that the second variable will be int
I suspect the printf() issue is a red herring, since with a null-terminated "Abc" will ignore other arguments.
Have you debugged your program? If not can you be sure the fault isn't in getch()?
I cannot duplicate your issue but then I commented out the getch() for simplicity.
BTW, why did you not use fgetc() or getchar()? Are you intending to use curses in a larger program?
===== Added after your edit =====
Okay, not a red herring, just a mistake by the OP.
C++ does allow allocating an array with the size specified by a variable; you've essentially done this with random (garbage) size and overflowed the stack, as you deduced. When you compile with C++ you are typically no longer compiling C and the rules change (depending on the particular compiler).
That said, I don't understand your question - you need to be a lot more clear with "when we take size of array through user input" ...