AI Features

Common Errors

Learn to avoid common mistakes in pointer code.

Pointer to local variables

Let’s explore a common problem found in pointer-intensive code using the example below:

C
#include <stdio.h>
int *doubleNum(int x)
{
int y = x * 2;
int *ptr = &y;
return ptr;
}
int main()
{
int *result = doubleNum(5);
printf("Result is %d\n", *result);
return 0;
}

We changed doubleNum to return a pointer to the result instead of returning the result directly.

In line 5, y contains the result of the computation. Then, on lines 7 and 8, we create a pointer to y and return it.

Inside main, at line 15, we dereference the pointer to get the value.

Run ...