My C function code keeps giving me errors, and I can't figure out whats wrong.
int * myfunc(int a)
{
int * newNum, i;
i = a*a;
*newNum = i;
return newNum;
}
My C function code keeps giving me errors, and I can't figure out whats wrong.
int * myfunc(int a)
{
int * newNum, i;
i = a*a;
*newNum = i;
return newNum;
}
There are three types of memory or variables, automatic like in your function, static and manual. Automatic lasts while scope lasts. Static is if you declare it with static:
static int i;
It lives while program is alive. Like global variable. And finally manual where you use malloc and free to allocate and free memory. Naturally you would like to assign address of variable to pointer before return, like this:
int * newPointer = &i;
If variable is static it will keep value through function calls. Code avoids warning from compiler about returning address of local variable via assigning address of local variable to pointer so it may be good idea to run on it some kind of tool like Lint or Splint, here is discussion about such tools
Look, newNum
is a pointer to integer. So the purpose of newNum
is to hold the address
of any integer.
When you declared
int * newNum;
newNum
is then pointing some garbage.
The following lines,
*newNum = i;
means the content of newNum
will be updated by i
. But did you forget, newNum
holds some garbage address? Hence the value of i
is assigned some garbage location
.
You may try this:
/**
* The following function will take an integer pointer from the caller.
* Its callers duty to check whether the pointer is initialed or not.
*/
void myfunc(int * newNum) {
// the content of the newNum pointer points will be updated
// as the memory address is sent here, we need not to return anything
*newNum = (*newNum) * (*newNum);
}
int main() {
int someInteger = 4;
int *ptr = &someInteger;
myfunc(ptr);
printf("Content of the pointer: %d", *ptr);
return 0;
}
You will get the output like,
Content of the pointer: 16