Using pointers in functions and modifying main() - c

I would like to pass a pointer as an argument into a function that normalizes the vector pointer that was passed as an argument.
Here are the functions:
float norm(Vector *v) {
float len;
len = sqrt(pow(v->x, 2.0) + pow(v->y, 2.0) + pow(v->z, 2.0));
return len;
}
Vector normalize(Vector *vec){
Vector normVec;
//calls norm function which also takes a pointer of vector type as argument
float norm = norm(&vec);
normVec.x = vec->x/norm;
normVec.y = vec->y/norm;
normVec.z = vec->z/norm;
return normVec;
}
I get this error:
error: called object ‘norm’ is not a function or function pointer.
How can I get this function running smoothly?

That is because your float norm variable shadows the norm() function.
Name one of them something else.
Also, vec is already a pointer, no need to take its address (&vec) when you pass it to norm()

Related

How to send back the values inside a void function to main function in C?

How can I send back the value inside a void function to the main function if the condition restricts me from using the non-void function to return those values?
here's my example code:
void calcTotalPaid(float total){
float totalPaid=0;
totalPaid += total;
}
You should pass a pointer to a variable that will receive the result and use that.
#include <stdio.h>
void calcTotalPaid(float* res, float total){
float totalPaid=0;
totalPaid = totalPaid + total;
*res = totalPaid;
}
int main(void) {
float value = 0;
calcTotalPaid(&value, 3.14);
printf("%f\n", value);
return 0;
}
Here is the explanation:
If you use a void function then it never returns a value into a called function which is here int main(). It shows an error.
You are passing the argument value into the parameter (a local variable that is declared when declaring the function prototype), so what if you pass the address of that argument into the calling function? Yes, using a pointer variable, you should pass the argument memory location.
In the called function, you have the memory address of that particular argument. Whenever the new values are inserted into that argument (which is now a local variable), it saves on that memory location because we have here that address of memory location.
Here is your program:
#include<stdio.h>//preprocessor directive for function printf()
void calTotalPaid (float *pointer, float total)//function declartion and
//definition of function
{
float totalpaid = 0;
totalpaid = totalpaid + total;
*pointer = totalpaid;
}
int main ()
{
float value, total = 0;
calTotalPaid (&value, total);//calling the function and passing the memory
//location to the function parameter so if function changed the value stored
//at value's memory location it will change in entire program.
printf ("The value is %f\n", value);
return 0;
}
use call by reference technique. Pass address of a variable from main to calcTotalPaid(), and store the address in a pointer variable.
void calcTotalPaid(float * total_paid , float total){
*total_paid = 0 + total;
}

Function using arrays as arguments in C

Just started learning pointers in C and I was faced with the following code:
#include <stddef.h>
#include <stdlib.h>
double *vec( double a[], double b[]);
int main(){
double v1[3]={1.0,1.0,1.0};
double v2[3]={1.0,-1.0,1.0};
double *v3 = NULL;
v3 = vec(v1,v2);
printf("v1 X v2 = (%f, %f, %f)\n",v3[0],v3[1],v3[2]);
free( v3);
return 0;
}
double *vec( double a[], double b[]){
double *c=NULL;
c = (double *)malloc(3*sizeof( double ));
c[0]= a[1]*b[2]-a[2]*b[1];
c[1]=-(a[0]*b[2]-a[2]*b[0]);
c[2]= a[0]*b[1]-a[1]*b[0];
return c;
}
The question here is, when declaring the function the author used *function(parameters) instead of function(parameters). Why did he/she used a pointer in to declare the function vec?
You read the syntax wrong. It is not *function it is a function returning double * aka a pointer to a double.
In C when you need dynamically allocated arrays you do this using pointers. Also C doesn't allow returning arrays from a function directly and therefore you have to return a pointer to its memory. (Watch out as local variables will get disposed)
To answer your specific question: You cannot return a "true" array in C. You can return a pointer to the beginning of the array, however.
To be honest, the code you are facing/studying is not the best. I could understand if vec( ) returned a malloc'ed pointer because it didn't know how big the input arrays were going to be. But the [partial] give-away is that vec( ) receives no parameter describing how many elements are in the array (an array parameter by itself cannot tell you this). (I say partial because the array might have been self-terminating via eg. a 0 value, just like C-style strings use).
But the implementation of vec( ) shows that it expects 3-element arrays, so returning a malloc'ed pointer is a little unnecessary. It would be much faster (and safer) for vec to have a third argument (array) passed in to receive the result. That way there is no dynamic memory allocation or freeing, and no opportunity to forget to free.
There is still the possibility, however, of the arrays being the incorrect size. You could workaround this by having a struct that holds a 3-element array of double, and passing in the structs (via pointers) instead, eg:
struct DoubleArray3
{
double values[ 3 ];
}
vec( const DoubleArray3* v1, const DoubleArray3* v2, DoubleArray3* result );
Function is defined as
Return_type Name_of_function(argument_list)
Return_type can be int,float,double,int*(indicate return type is integer pointer ) , float*,char* etc.
here return type of function is double* means function will return a value of type double pointer (C is declared as double* as it is variable which is returned from function )

What are Function Pointers?

What are Function Pointers in plain English?
In simple english,
A FUNCTION_POINTER is a pointer which points towards the address of
fuction's first instruction, like a POINTER which points towards the
address of a variable.
Take a example of a program to understand the concept
Sum of all integers upto the user i/p
-
#include <stdio.h>
int IsAny(long n)
{
return 1;
}
long AddIf(long limit, int (*funPointer)(long))
{
long sum = 0;
register int i;
for(i = 1; i <= limit; ++i)
{
if(funPointer(i))
sum += i;
}
return sum;
}
int main(void)
{
long l, total;
printf("Enter a positive integer: ");
scanf("%ld", &l);
total = AddIf(l, IsAny);
printf("Sum of all integers upto %ld is %ld\n", l, total);
}
Here FUNCTION_POINTER is called to call IsAny function in AddIf with a declaration
as int (*funPointer)(long)) in AddIf function
As you asked in plain english, let's give it a try.
A pointer is an address in memory. A pointer has a type so the program can "find" the object you are refering to when using your pointer.
A function pointer uses the same logic. It declares a function that will be used has a method parameter for exemple. So you know that you will use a function that will have an input and an ouput in that method but the logic in that function don't need to be known.
From there you can send any function pointer to be used as the program only concern is that you will send and receive predefined types.
According wiki
A function pointer (or subroutine pointer or procedure pointer) is a type of pointer supported by third-generation programming languages (such as PL/I, COBOL, Fortran,1 dBASE dBL, and C) and object-oriented programming languages (such as C++ and D).2 Instead of referring to data values, a function pointer points to executable code within memory. When dereferenced, a function pointer can be used to invoke the function it points to and pass it arguments just like a normal function call. Such an invocation is also known as an "indirect" call, because the function is being invoked indirectly through a variable instead of directly through a fixed name or address. Function pointers can be used to simplify code by providing a simple way to select a function to execute based on run-time values.
Pointer = That hold the address of a variable or means simple memory.
As same like pointer , function pointer that hold the address of a function.
Syntax :
return type (*fp) (argument);
Example:
void f1()
{
printf("in function f1");
}
int main()
{
/* declaring a function pointer
* argument void
* return type is also void
*/
void (*fun_ptr) (void);
fun_pt= f1(); // fun_pthold the address of f1
(*fun_pt)(); // calling a function f1
}

pointers to functions explanation in C

I don't quite understand the purpose of this. I have searched and read what seems to be the same thing on different sources, but none of them give an explanation as to what it does specifically and what is it's purpose.
can anyone help me understand this
Let's take a look in the Standard C library:
void qsort(void *BASE, size_t NMEMB, size_t SIZE,
int (*COMPAR)(const void *, const void *) );
the last argument of qsort is pointer to compare function. the compare function is used to compare two elements from the array (it defines the ordering).
If qsort() wouldn't be using function pointer we would have to write over and over again qsort() if we have different ordering requirement or new types/struct we would like to sort.
Take the following:
int i = 10;
A corresponding pointer can be defined like this:
int* p = &i;
Variable "p" is very similar to "i", in that they are both numbers. However, the value of 'p' is the memory address of variable 'i', in other words, it is the exact memory address where value 10 is stored. Furthermore, 'p' knows the type of the value at that memory address. It knows it is an "int", since it was defined as "int" + "star".
Similarly, consider a function:
int m(char* arg1, double arg2)
{
/* do something */
}
C provides the ability to access the memory address of where this function is stored. A function is not like a value, e.g. it cannot be changed, so when one says the memory address of a function, this actually means the memory address where the code of the function is located, e.g. whatever is written between the curly braces.
However, there is a similarity between a function and a variable. They both have a type. A function's type is comprised of:
Return Type
Parameter Type List, namely:
Type of parameter #1
Type of parameter #2
...
Type of parameter #N
C treats all functions that have the same return type and parameter type lists as "the same type of function". Similar to how two variables declared as "int i,j" are considered to be the same type, so are two functions with the same signature considered the same type.
The syntax for describing the type of a function includes the bare minimum: the return type and the types of each parameter (in the right order):
return-type (* <variable-name>)(Type-of-Param-1, Type-of-Param-2, ..., Type-of-Param-N)
In effect, in order to declare a pointer to function 'm' above:
int (*p)(char*, double) = &m;
"int" is the return type of method 'm', the fir pair of round brackets and the star are part of the syntax, 'p' is the variable name, "char*" is the type of the first parameter, and "double" is the tyep of the second parameter. There is no reference to the parameter names -- as the names of the parameters are not relevant to the type/signature of a function.
Note that similar to a variable, the address of a method is obtained exactly the same as for a variable, i.e. by prepending it with an ampersand.
Pointers to functions can be passed around simlar to pointers to variables, and more importantly, the code of the function at that particular memory address can be invoked. For example, in order to invoke function 'm' by means of pointer 'p', it would take something like this:
int result = p(NULL, 10.0);
int result = (*p) (NULL, 10.0); // alternative syntax
The typical example is a sorting function that needs you to "point" it to a function that can compare two elements. You pass this function a pointer to your comparison function so that it can call your function when it needs to do a comparison. You can't actually pass the function, but you can pass it a pointer to a function, which is just a variable that "points" to where your function is in memory. The sorting function can call your function by using this pointer. Pointers, in general, are just variables that store a memory address. That memory address is what it's "pointing" to, and it can be anything at that address - a function, an integer, a series of character variables that end with a null character. Function pointers are just variables that store the memory address of where a function is in memory so that the function can be called by some other piece of code.
Hope that explanation helps.
It is no more simple then this.
When you know how and why pointers work with normal variables, think of using these pointers, but this time with functions. That is, you replace the address of variables now with the address of the function, with all the power of pointers there, you can now access function indirectly by using the pointers that point to them instead of using their names directly.
From http://www.cplusplus.com/doc/tutorial/pointers/
// my first pointer
#include <iostream>
using namespace std;
int main ()
{
int firstvalue, secondvalue;
int * mypointer;
mypointer = &firstvalue;
*mypointer = 10;
mypointer = &secondvalue;
*mypointer = 20;
cout << "firstvalue is " << firstvalue << endl;
cout << "secondvalue is " << secondvalue << endl;
return 0;
}
And the output for the above is
firstvalue is 10
secondvalue is 20
Now from http://www.newty.de/fpt/intro.html#what
We have function pointers.
//------------------------------------------------------------------------------------
// 1.2 Introductory Example or How to Replace a Switch-Statement
// Task: Perform one of the four basic arithmetic operations specified by the
// characters '+', '-', '*' or '/'.
// The four arithmetic operations ... one of these functions is selected
// at runtime with a swicth or a function pointer
float Plus (float a, float b) { return a+b; }
float Minus (float a, float b) { return a-b; }
float Multiply(float a, float b) { return a*b; }
float Divide (float a, float b) { return a/b; }
// Solution with a switch-statement - <opCode> specifies which operation to execute
void Switch(float a, float b, char opCode)
{
float result;
// execute operation
switch(opCode)
{
case '+' : result = Plus (a, b); break;
case '-' : result = Minus (a, b); break;
case '*' : result = Multiply (a, b); break;
case '/' : result = Divide (a, b); break;
}
cout << "Switch: 2+5=" << result << endl; // display result
}
// Solution with a function pointer - <pt2Func> is a function pointer and points to
// a function which takes two floats and returns a float. The function pointer
// "specifies" which operation shall be executed.
void Switch_With_Function_Pointer(float a, float b, float (*pt2Func)(float, float))
{
float result = pt2Func(a, b); // call using function pointer
cout << "Switch replaced by function pointer: 2-5="; // display result
cout << result << endl;
}
// Execute example code
void Replace_A_Switch()
{
cout << endl << "Executing function 'Replace_A_Switch'" << endl;
Switch(2, 5, /* '+' specifies function 'Plus' to be executed */ '+');
Switch_With_Function_Pointer(2, 5, /* pointer to function 'Minus' */ &Minus);
}
As you will see from the above call, the address of Minus() function is passed which is then in passed on to call the actual function via pointer and in this case, pt2Func(...).
Note that in the case of function pointers you will take care of the function signature as well.
float (*pt2Func)(float, float)
float Minus (float a, float b) { return a-b; }
As you can see above, the signatures are the same, so you can pass in any function address and the call will work.
I hope this helps.
Function pointers are used to dynamicly call functions. You could for example take a function pointer as an argument to another function and in a sense provide additional functionality in that way. You could also create structs that have function pointers and thus a sort of member functions, like for classes. This could be usefull if you have a function that works on your structs but they can be a bit different in what work should actually be done with them. For example:
// Structures for our "objects"
typedef int funcPtr();
struct foo {
int a;
int b;
funcPtr* run;
}
struct bar {
int a;
int b;
funcPtr* run;
char* s;
}
// Functions that we will use as our "member functions"
int runOne() {
return 1;
}
int runTwo() {
return 2;
}
// Functions to create objects... kinda like new operators
struct foo* NewFoo(int aVal, int bVal) {
struct foo* this = (stuct foo*)malloc(sizeof(struct foo));
this->a = aVal;
this->b = bVal;
this->run = runOne;
return this;
}
struct bar* NewBar(int aVal, int bVal) {
struct bar* this = (stuct bar*)malloc(sizeof(struct bar));
this->a = aVal;
this->b = bVal;
this->run = runTwo;
return this;
}
// Create "objects"
struct foo* myFoo = NewFoo(10, 20);
struct bar* myBar = NewBar(30, 40);
// Run the run function on them (which actually runs different functions for each "object")
int result1 = myFoo->run();
int result2 = myBar->run();
result1 will now be 1 and result2 will be 2. This can be used if you have structs containing different kinds of "modules" with a similar interface but with different behavior for example.

Understanding functions and pointers in C

This is a very simple question but what does the following function prototype mean?
int square( int y, size_t* x )
what dose the size_t* mean? I know size_t is a data type (int >=0). But how do I read the * attached to it? Is it a pointer to the memory location for x? In general I'm having trouble with this stuff, and if anybody could provide a handy reference, I'd appreciate it.
Thanks everybody. I understand what a pointer is, but I guess I have a hard hard time understanding the relationship between pointers and functions. When I see a function prototype defined as int sq(int x, int y), then it is perfectly clear to me what is going on. However, when I see something like int sq( int x, int* y), then I cannot--for the life of me--understand what the second parameter really means. On some level I understand it means "passing a pointer" but I don't understand things well enough to manipulate it on my own.
How about a tutorial on understanding pointers?
In this case however, the pointer is probably used to modify/return the value. In C, there are two basic mechanisms in which a function can return a value (please forgive the dumb example):
It can return the value directly:
float square_root( float x )
{
if ( x >= 0 )
return sqrt( x );
return 0;
}
Or it can return by a pointer:
int square_root( float x, float* result )
{
if ( x >= 0 )
{
*result = sqrt( result );
return 1;
}
return 0;
}
The first one is called:
float a = square_root( 12.0 );
... while the latter:
float b;
square_root( 12.00, &b );
Note that the latter example will also allow you to check whether the value returned was real -- this mechanism is widely used in C libraries, where the return value of a function usually denotes success (or the lack of it) while the values themselves are returned via parameters.
Hence with the latter you could write:
float sqresult;
if ( !square_root( myvar, &sqresult ) )
{
// signal error
}
else
{
// value is good, continue using sqresult!
}
*x means that x is a pointer to a memory location of type size_t.
You can set the location with x = &y;
or set the value were x points to with: *x = 0;
If you need further information take a look at: Pointers
The prototype means that the function takes one integer arg and one arg which is a pointer to a size_t type. size_t is a type defined in a header file, usually to be an unsigned int, but the reason for not just using "unsigned int* x" is to give compiler writers flexibility to use something else.
A pointer is a value that holds a memory address. If I write
int x = 42;
then the compiler will allocate 4 bytes in memory and remember the location any time I use x. If I want to pass that location explicitly, I can create a pointer and assign to it the address of x:
int* ptr = &x;
Now I can pass around ptr to functions that expect a int* for an argument, and I can use ptr by dereferencing:
cout << *ptr + 1;
will print out 43.
There are a number of reasons you might want to use pointers instead of values. 1) you avoid copy-constructing structs and classes when you pass to a function 2) you can have more than one handle to a variable 3) it is the only way to manipulate variables on the heap 4) you can use them to pass results out of a function by writing to the location pointed to by an arg
Pointer Basics
Pointers And Memory
In response to your last comment, I'll try and explain.
You know that variables hold a value, and the type of the variable tells you what kind of values it can hold. So an int type variable can hold an integer number that falls within a certain range. If I declare a function like:
int sq(int x);
...then that means that the sq function needs you to supply a value which is an integer number, and it will return a value that is also an integer number.
If a variable is declared with a pointer type, it means that the value of that variable itself is "the location of another variable". So an int * type variable can hold as its value, "the location of another variable, and that other variable has int type". Then we can extend that to functions:
int sqp(int * x);
That means that the sqp function needs to you to supply a value which is itself the location of an int type variable. That means I could call it like so:
int p;
int q;
p = sqp(&q);
(&q just means "give me the location of q, not its value"). Within sqp, I could use that pointer like this:
int sqp(int * x)
{
*x = 10;
return 20;
}
(*x means "act on the variable at the location given by x, not x itself").
size_t *x means you are passing a pointer to a size_t 'instance'.
There are a couple of reasons you want to pass a pointer.
So that the function can modify the caller's variable. C uses pass-by-value so that modifying a parameter inside a function does not modify the original variable.
For performance reasons. If a parameter is a structure, pass-by-value means you have to copy the struct. If the struct is big enough this could cause a performance hit.
There's a further interpretation given this is a parameter to a function.
When you use pointers (something*) in a function's argument and you pass a variable you are not passing a value, you are passing a reference (a "pointer") to a value. Any changes made to the variable inside the function are done to the variable to which it refers, i.e. the variable outside the function.
You still have to pass the correct type - there are two ways to do this; either use a pointer in the calling routine or use the & (addressof) operator.
I've just written this quickly to demonstrate:
#include <stdio.h>
void add(int one, int* two)
{
*two += one;
}
int main()
{
int x = 5;
int y = 7;
add(x,&y);
printf("%d %d\n", x, y);
return 0;
}
This is how things like scanf work.
int square( int y, size_t* x );
This declares a function that takes two arguments - an integer, and a pointer to unsigned (probably large) integer, and returns an integer.
size_t is unsigned integer type (usually a typedef) returned by sizeof() operator.
* (star) signals pointer type (e.g. int* ptr; makes ptr to be pointer to integer) when used in declarations (and casts), or dereference of a pointer when used at lvalue or rvalue (*ptr = 10; assigns ten to memory pointed to by ptr). It's just our luck that the same symbol is used for multiplication (Pascal, for example, uses ^ for pointers).
At the point of function declaration the names of the parameters (x and y here) don't really matter. You can define your function with different parameter names in the .c file. The caller of the function is only interested in the types and number of function parameters, and the return type.
When you define the function, the parameters now name local variables, whose values are assigned by the caller.
Pointer function parameters are used when passing objects by reference or as output parameters where you pass in a pointer to location where the function stores output value.
C is beautiful and simple language :)
U said that u know what int sq(int x, int y) is.It means we are passing two variables x,y as aguements to the function sq.Say sq function is called from main() function as in
main()
{
/*some code*/
x=sr(a,b);
/*some other code*/
}
int sq(int x,int y)
{
/*code*/
}
any operations done on x,y in sq function does not effect the values a,b
while in
main()
{
/*some code*/
x=sq(a,&b);
/*some other code*/
}
int sq(int x,int* y)
{
/*code*/
}
the operations done on y will modify the value of b,because we are referring to b
so, if you want to modify original values, use pointers.
If you want to use those values, then no need of using pointers.
most of the explanation above is quite well explained. I would like to add the application point of view of this kind of argument passing.
1) when a function has to return more than one value it cannot be done by using more than one return type(trivial, and we all know that).In order to achieve that passing pointers to the function as arguments will provide a way to reflect the changes made inside the function being called(eg:sqrt) in the calling function(eg:main)
Eg: silly but gives you a scenario
//a function is used to get two random numbers into x,y in the main function
int main()
{
int x,y;
generate_rand(&x,&y);
//now x,y contain random values generated by the function
}
void generate_rand(int *x,int *y)
{
*x=rand()%100;
*y=rand()%100;
}
2)when passing an object(a class' object or a structure etc) is a costly process (i.e if the size is too huge then memory n other constraints etc)
eg: instead of passing a structure to a function as an argument, the pointer could be handy as the pointer can be used to access the structure but also saves memory as you are not storing the structure in the temporary location(or stack)
just a couple of examples.. hope it helps..
2 years on and still no answer accepted? Alright, I'll try and explain it...
Let's take the two functions you've mentioned in your question:
int sq_A(int x, int y)
You know this - it's a function called sq_A which takes two int parameters. Easy.
int sq_B(int x, int* y)
This is a function called sq_B which takes two parameters:
Parameter 1 is an int
Parameter 2 is a pointer. This is a pointer that points to an int
So, when we call sq_B(), we need to pass a pointer as the second
parameter. We can't just pass any pointer though - it must be a pointer to an int type.
For example:
int sq_B(int x, int* y) {
/* do something with x and y and return a value */
}
int main() {
int t = 6;
int u = 24;
int result;
result = sq_B(t, &u);
return 0;
}
In main(), variable u is an int. To obtain a pointer to u, we
use the & operator - &u. This means "address of u", and is a
pointer.
Because u is an int, &u is a pointer to an int (or int *), which is the type specified by parameter 2 of sq_B().
Any questions?

Resources