Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to define a pointer without a temp/aux variable? (Or would this be bad C-coding?)

Tags:

c

pointers

I'm trying to understand C-pointers. As background, I'm used to coding in both C# and Python3.

I understand that pointers can be used to save the addresses of a variable (writing something like type* ptr = &var;) and that incrementing pointers is equivalent to incrementing the index of an array of objects of that object type type. But what I don't understand is whether or not you can use pointers and deferenced objects of the type (e.g. int) without referencing an already-defined variable.

I couldn't think of a way to do this, and most of the examples of C/C++ pointers all seem to use them to reference a variable. So it might be that what I'm asking is either impossible and/or bad coding practice. If so, it would be helpful to understand why.

For example, to clarify my confusion, if there is no way to use pointers without using predefined hard-coded variables, why would you use pointers at all instead of the basic object directly, or arrays of objects?

There is a short piece of code below to describe my question formally.

Many thanks for any advice!

// Learning about pointers and C-coding techniques.

#include <stdio.h>

/* Is there a way to define the int-pointer age WITHOUT the int variable auxAge? */

int main()  // no command-line params being passed
{
    int auxAge = 12345;
    int* age = &auxAge;
    // *age is an int, and age is an int* (i.e. age is a pointer-to-an-int, just an address to somewhere in memory where data defining some int is expected)
    // do stuff with my *age int e.g. "(*age)++;" or "*age = 37;"
    return 0;
}
like image 481
Gregory Fenn Avatar asked Oct 16 '25 20:10

Gregory Fenn


1 Answers

Yes, you can use dynamic memory (also known as "heap") allocation:

#include <stdlib.h>

int * const integer = malloc(sizeof *integer);
if (integer != NULL)
{
  *integer = 4711;
  printf("forty seven eleven is %d\n", *integer);
  free(integer);
  // At this point we can no longer use the pointer, the memory is not ours any more.
}

This asks the C library to allocate some memory from the operating system and return a pointer to it. Allocating sizeof *integer bytes makes the allocation fit an integer exactly, and we can then use *integer to dereference the pointer, that will work pretty much exactly like referencing an integer directly.

like image 73
unwind Avatar answered Oct 18 '25 11:10

unwind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!