Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While trying to understand a pointer, I have the following concern

In last two statements, any real difference between the realPointer and fakePointer. Will they both provide the same functionality?

  int num = 0;

  int *realPointer = #
  int fakePointer = #
like image 446
Yet A-beyene Avatar asked Mar 11 '16 12:03

Yet A-beyene


People also ask

Which of the following uses pointer to variables rather than variables names?

However, scanf uses pointers to variables, not variables themselves. For example, the following code reads an integer from the keyboard: int my_integer; scanf ("%d", &my_integer);

What is a pointer where we use it?

What is a Pointer? A pointer is a variable that stores a memory address. Pointers are used to store the addresses of other variables or memory items. Pointers are very useful for another type of parameter passing, usually referred to as Pass By Address.

What is uintptr_ t in C?

uintptr_t is an unsigned integer memsize-type that can safely store a pointer regardless of the platform capacity. The type uintptr_t is similar to the types size_t and UINT_PTR.

Which arithmetic operations can be performed on pointers?

You can perform a limited number of arithmetic operations on pointers. These operations are: Increment and decrement. Addition and subtraction.


2 Answers

A variable declared as a pointer is semantically different from a variable not declared as a pointer. The compiler (and the language) will allow you do do things with a pointer you can not do with a non-pointer. And the opposite of course.

The biggest different is that you can dereference a pointer, but you can't do that to a non-pointer.

For example, using the variables in your code, then we can do *realPointer = 5 to make num be assigned the value 5, but doing *fakePointer = 5 is not allowed and doesn't make sense since fakePointer isn't actually a pointer.

like image 29
Some programmer dude Avatar answered Oct 07 '22 01:10

Some programmer dude


int fakePointer = #

This is not valid C, it breaks the rules of simple assignment and will not compile.

However, had you done int fakePointer = (int)# then the only difference would be that there are no guarantees that you can use fakePointer reliably, conversions from pointers to integers are implementation-defined and could potentially also lead to undefined behavior (6.3.2.3):

Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type.

To safely and portably convert between pointers and integers, you should not use int but the type uintptr_t found in stdint.h.

like image 119
Lundin Avatar answered Oct 07 '22 01:10

Lundin