I'm a beginner in C language and in my previous question I have asked about proper function declaration order in C. I was told that in standard C, it is necessary to declare functions before calling them.
But for the following example code I cannot declare the the function times2p before the main(). I tried to declare it as: void times2(int in_data); right before the main(), but I get errors. Here below is the example code:
#include <stdio.h>
#include <stdlib.h>
void times2p(int *in_data);
void times2(int in_data);
int main()
{
int y = 5;
int s = times2(y);
printf("%d\n", y);
printf("%d\n", s);
printf("-------------\n");
int yp = 5;
times2p(&yp);
printf("%d\n", yp);
return 0;
}
//Multiplies the input argument by two
void times2(int in_data){
in_data = in_data*2;
}
void times2p(int *in_data){
*in_data = *in_data*2;
}
How and where should the times2p function be declared in this case? If I don't declare the code still compiles without error but I was told that I have to declare the functions in C in my previous question.
Here is the error:
||=== Build: Debug in test1 (compiler: GNU GCC Compiler) ===|
C:\Users\nnn\Documents\CodeBlocks\test1\main.c||In function 'main':|
C:\Users\nnn\Documents\CodeBlocks\test1\main.c|16|error: void value not ignored as it ought to be|
C:\Users\nnn\Documents\CodeBlocks\test1\main.c|13|warning: unused variable 'read_x' [-Wunused-variable]|
||=== Build failed: 1 error(s), 1 warning(s) (0 minute(s), 0 second(s)) ===|
Your code in the current version of the question is incorrect, but not for the reason you're asking about.
There's nothing wrong with the void function declarations before main, and the compiler doesn't complain about them. The problem is that a void function doesn't return a value, and you're trying to call them as if they did:
int s = times2(y);
This would be correct only if times2(y) returned an int value (or a value of some type implicitly convertible to int).
Also, looking at the definition of the function:
void times2(int in_data){
in_data = in_data*2;
}
The parameter in_data is a local variable within the function. Changing its value effectively does nothing.
Your times2p function looks OK, and it should work. If you want times2() to be useful, it needs to return a value:
int times2((int in_data) {
return in_data * 2;
}
(The question has changed, so this answer may not be perfect anymore, sorry).
You need to declare at least the prototype of the functions before you use it. Like this:
#include <stdio.h>
#include <stdlib.h>
//How should the function times2p be declared here?
void times2p(int *in_data);
int main()
{
int y = 5;
times2p(&y);
printf("%d\n", y);
return 0;
}
//Multiplies the input argument by two
void times2p(int *in_data){
*in_data = *in_data*2;
}
Or declare the function itself, like this:
#include <stdio.h>
#include <stdlib.h>
//Multiplies the input argument by two
void times2p(int *in_data){
*in_data = *in_data*2;
}
int main()
{
int y = 5;
times2p(&y);
printf("%d\n", y);
return 0;
}
Related
I have been encountering this problem when I try to compile in C. When I asked help50 for help, it gave me this message "By "undefined reference," clang means that you've called a function, print, that doesn't seem to be implemented. If that function has,
in fact, been implemented, odds are you've forgotten to tell clang to "link" against the file that implements print. Did you forget to
compile with -lfoo, where foo is the library that defines print?" Because of this, I decided to implement #include <foo.h>, however after I tried to compile, I received a fatal error message. This is my code
#include <cs50.h>
#include <stdio.h>
void print(char c, int n);
//Code
int main(void)
{
int n;
do
{
n = get_int("Height:");
} while(n < 1 || n > 8);
for(int i = 0; i < n; i++)
{
print(' ', n - 1 - i);
print('#', i + 1);
print(' ', 2);
print('#', i + 1);
printf("\n");
}
}
`
You have declared print... But where is the implementation?
The declaration is just a promise to the compiler that you have a function that take some parameters of a given type and return something a given type.
When the compiler sees you calling the function it will how to report errors if the types don't match...
The implementation is where the compiler knows what to do with the parameters in order to return something from that function.
Here is a sample implementation:
void print(char c, int n)
{
printf("My char is %c and my int is %d\n", c, n);
}
There's no standard library print() function in C. You haven't actually defined it anywhere, either.
I have a struct that contains a declaration like this one:
void (*functions[256])(void) //Array of 256 functions without arguments and return value
And in another function I want to define it, but there are 256 functions!
I could do something like this:
struct.functions[0] = function0;
struct.functions[1] = function1;
struct.functions[2] = function2;
And so on, but this is too tiring, my question is there some way to do something like this?
struct.functions = { function0, function1, function2, function3, ..., };
EDIT: Syntax error corrected as said by Chris Lutz.
I have a struct that contains a declaration like this one:
No you don't. That's a syntax error. You're looking for:
void (*functions[256])();
Which is an array of function pointers. Note, however, that void func() isn't a "function that takes no arguments and returns nothing." It is a function that takes unspecified numbers or types of arguments and returns nothing. If you want "no arguments" you need this:
void (*functions[256])(void);
In C++, void func() does mean "takes no arguments," which causes some confusion (especially since the functionality C specifies for void func() is of dubious value.)
Either way, you should typedef your function pointer. It'll make the code infinitely easier to understand, and you'll only have one chance (at the typedef) to get the syntax wrong:
typedef void (*func_type)(void);
// ...
func_type functions[256];
Anyway, you can't assign to an array, but you can initialize an array and copy the data:
static func_type functions[256] = { /* initializer */ };
memcpy(mystruct.functions, functions, sizeof(functions));
I had the same problem, this is my small program to test the solution. It looks pretty straightforward so I thought I'd share it for future visitors.
#include <stdio.h>
int add(int a, int b) {
return a+b;
}
int minus(int a, int b) {
return a-b;
}
int multiply(int a, int b) {
return a*b;
}
typedef int (*f)(int, int); //declare typdef
f func[3] = {&add, &minus, &multiply}; //make array func of type f,
//the pointer to a function
int main() {
int i;
for (i = 0; i < 3; ++i) printf("%d\n", func[i](5, 4));
return 0;
}
You can do it dynamically... Here is a small example of a dynamic function array allocated with malloc...
#include <stdio.h>
#include <stdlib.h>
typedef void (*FOO_FUNC)(int x);
void a(int x)
{
printf("Function a: %d\n", x);
}
void b(int x)
{
printf("Function b: %d\n", x);
}
int main(int argc, char **argv)
{
FOO_FUNC *pFoo = (FOO_FUNC *)malloc(sizeof(FOO_FUNC) * 2);
pFoo[0] = &a;
pFoo[1] = &b;
pFoo[0](10);
pFoo[1](20);
return 0;
}
From the top of my head and untested.
// create array of pointers to functions
void (*functions[256])(void) = {&function0, &function1, &function2, ..., };
// copy pointers to struct
int i;
for (i = 0; i < 256; i++) struct.functions[i] = functions[i];
EDIT: Corrected syntax error as said by Chris Lutz.
You could do that while declaring your struct instance:
function_structur fs = { struct_field1,
struct_field2,
{function0, function1, ..., function255},
struct_field3,
... };
You cannot use this shortcut for initialize arrays after the array has been declared: if you need to do that, you'll have to do it dynamically (using a loop, a memcpy or something else).
If you want to post-initialize an array using form like {func1, func2, ...}, this can be accomplished in the following way (using GCC):
UPD (thanks to Chris Lutz for remarks)
Define a macro like this:
#define FUNCTION_VECTOR_COPY(destVec, sourceVec) memcpy(destVec, sourceVec, sizeof(sourceVec))
And pass source vector using Compound Literals, as follow:
#include <string.h>
...
void (*functions[256])();
...
FUNCTION_VECTOR_COPY (functions, ((void(*[])()) {func1, func2, func3}));
I am learning pointers and going through the examples from this Stanford PDF
Stanford Pointers Guide
I decided to write some code using their examples to get a better handle on what is happening. I am working from page 21 of the PDF.
When I run the code I get a segmentation fault, so I know that I'm trying to access memory that doesn't belong to me, but I don't understand where I'm going wrong.
Here is the code I have written:
#include <stdio.h>
#include <stdlib.h>
// function prototypes
void C();
void B();
void main(){
int *worthRef;
int num = 42;
worthRef = #
B(*worthRef);
}
// Takes value of interest by reference and adds 2
void C(int* worthRef){
*worthRef = *worthRef + 2;
printf("num = %d", &worthRef);
}
// adds 1 to value of interest then calls C()
void B(int* worthRef){
*worthRef = *worthRef + 1; // add 1 to worthRef as before
C(worthRef); // NOTE: no & required. We already have a pointer to
// the value of interest, so it can be
// passed through directly
}
// function prototypes
void C();
void B();
That comment is a lie. Those are function declarations without a prototype (which is part of the problem in this code).
B(*worthRef);
This line calls B with an int. (Given the declaration int *worthRef, the type of *worthRef is int.)
void B(int* worthRef){
But here B expects to be given a pointer to an int, which is the bug: You're passing a number where a pointer is expected.
To fix this, change the call in main to B(worthRef) (or B(&num)), and change
printf("num = %d", &worthRef);
to
printf("num = %d\n", *worthRef);
If you had included a prototype in your function declarations, then the compiler would have warned you about the problem (probably):
// function prototypes
void C(int *);
void B(int *);
I have just written a sample program to understand the working of functions in C. I declared a function in C and call it during my programs execution. However my compiler gives me a warning saying unused function. My code looks like this :
#include <stdlib.h>
#include <stdio.h>
int test_function(x);
int main(){
int x;
char letter[] ={"HAAA"};
char cmpre[] = {"AHD"};
int value;
for(int i=0; i<4;i++)
{
if(letter[i] == cmpre[i])
{
x=0;
}
}
int test_function(x)
{
if (x==0)
{
printf("the letters are the same");
}
return value;
}
printf("To check if the letters are the same go to the function");
test_function(x);
return 0;
}
The program seems to execute fine but I get a warning in the fourth line where I declared the function in the start of the program. The warning is :
Multiple markers at this line
- parameter names (without types) in function declaration [enabled by
default]
- Unused declaration of function 'test_function'
I think the way I am calling my function is not right. Could somebody please help me. Thnak you in advance.
Disclaimer: nested functions are non-standard C and I only know (of) the GNU extension for this. As such anything I claim here may well be untrue in another implementation. My recommendation is that you just don't use them at all.
Your nested test_function is shadowing the global declaration. So the test_function you declared above main is never called, because the call inside main refers to the nested function. Hence, you get a warning.
You should declare int test_function outside of main
for example.
int test_function(int x)
and then call the function in main.
value = test_function(x)
This is what your code should look like:
#include <stdlib.h>
#include <stdio.h>
int test_function(x)
{
int value = 0;
if (x==0)
{
printf("the letters are the same");
}
return value;
}
int main(){
int x = 0;
char letter[] ={"HAAA"};
char cmpre[] = {"AHD"};
int value = 0; // unused
for(int i=0; i<4;i++)
{
if(letter[i] == cmpre[i])
{
x=0;
}
}
printf("To check if the letters are the same go to the function");
test_function(x);
return 0;
}
Note that if you dont need a return value you could make the function void.
And initialize your variables. You may search hours to find such a error
My purpose is to create an array in a function and then return it to the main function.
I was recommended to allocate the array on the heap in the function (otherwise popped from the stack as soon as its returned).
The code is shown below:
#include <stdlib.h>
int main() {
double *v1 = myFunction();
return 0;
}
double *myFunction() {
return malloc(10*sizeof(double));
}
When I compile this code with gcc I get the following error-message:
..\src\main3.c:38:9: error: conflicting types for 'myFunction'
What is wrong with this code? Why do I get this compilation error?
Provide myFunction()'s prototype before using it, that is before main() like so:
double * myFunction();
int main(void)
{
...
If not doing so, the compiler assumes type int for myFunction() when seeing it for the first time.
Than later it finds it to be declared as double * (being different from int) which then provokes the error.
Turning on all warnings would have pointed you to using a function without prototype. Use -Wall -Wextra -pedantic to turn on most of gcc's warnings.
Another issue is that declaring a function without any arguments specified leaves it open what to pass on calling the function:
double * myFunction();
If a function should be specfied to not have any arguments specify void as argument:
double * myFunction(void);
The same for how your code defines main(). It shall be:
int main(void);
or either be
int main(int argc, char ** argv);
1) Add prototype of myfunction at the starting like following or
double *myFunction();
int main() {
double *v1 = myFunction();
return 0;
}
double *myFunction() {
return malloc(10*sizeof(double));
}
2). or define the functionBody before it is called
double *myFunction() {
return malloc(10*sizeof(double));
}
int main() {
double *v1 = myFunction();
return 0;
}
However, first solution is preferable.
Your code is almost fine, there's only one little but blocking error, you are trying to use myFunction before the symbol is defined, all you have to do is :
#include <stdlib.h>
double *myFunction() { // myFunction should be declared before it's used
return malloc(10*sizeof(double));
}
int main() {
double *v1 = myFunction();
return 0;
}
The the open C book states "All identifiers in C need to be declared before they are used. This is true for functions as well as variables." the beauty in C is that you can do can do amazing stuff like this piece of code, but you should follow some guidelines, read the open C book!.
Cheers.
Try this..
return (double*) malloc(10*sizeof(double));