Arduino Forum

Community => Bar Sport => Topic started by: Rupert909 on Jul 02, 2016, 10:44 pm

Title: "Pointers make my head spin" etc ...
Post by: Rupert909 on Jul 02, 2016, 10:44 pm
I've seen this comment in various formats over the years.

Why do so many people feel like its a problem wrapping their heads around pointers?

Is it only because of the compact and cryptic notation, or is it rooted in a deeper lack of understanding computers?

On this forum, may it just be that so many non-programmers want to make stuff?
Title: Re: "Pointers make my head spin" etc ...
Post by: Rupert909 on Jul 02, 2016, 11:16 pm
Don't you know it is not polite to point? ;)

If I recall, variables contain a value. pointers contain a variable.
Am I correct, or should my head be spinning?

~Travis
Spin away! :-)
Title: Re: "Pointers make my head spin" etc ...
Post by: Rupert909 on Jul 02, 2016, 11:55 pm
clarification: it stores the address in memory of a variable.

~Travis
A pointer is a variable that explicitly stores a memory location, where data can be read from or written to.

Multiple pointers can point to the same location.

Behind the scenes, all variable names can be considered pointers, as they refer to locations in memory where the value of the variable is stored.   

So, pointers do not point to variables, but they may point to the memory cells where the value of a variable is stored.

Code: [Select]

int i=5;   // value 5 is stored in memory somewhere, and known by name i

int *ptr=&i;  // ptr points to memory location for variable i, where 5 is stored

(*ptr)=6;  // updates data at memory location pointed to by pointer



In this example, the value of variable 'i' will change, but that's not because the pointer knows anything about the variable, only that they refer to the same memory cells.

:-)
Title: Re: "Pointers make my head spin" etc ...
Post by: Oracle on Jul 03, 2016, 01:33 am
ok, so I was close.  :P

admittedly, I didn't look up the first answer, but I did the second. and further admission, I didn't read the whole article, but I have bookmarked it for future digestion.
The simple definition also don't do much to convey what they really are or why they're so powerful (which is the part that's hard to wrap your head around).

Imagine a class where one of the member variables is a pointer to an object in that class.  You can instantiate many objects and link them together to store large amounts of data, you can easily insert and remove objects from the list to keep them in order.  Try to implement an array where adding another value keeps it in alphabetical order with zero performance penalty for sorting.

Now add more than one pointer to the class.  You can have one pointer go to the next value alphabetically and the other go the next value according to some other criteria.  You can keep the same data sorted by multiple different keys with no performance cost.  With multiple pointers in a class, you can easily implement trees that have all sorts of rules to make them fast an efficient to traverse data. 

Pointers are a very powerful concept, but it's hard to get ones head around just what they represent on a simple reading.
Title: Re: "Pointers make my head spin" etc ...
Post by: Robin2 on Jul 03, 2016, 09:55 am
Is it only because of the compact and cryptic notation, or is it rooted in a deeper lack of understanding computers?
For me the concept pointers (the addresses of memory locations at which data is stored) is trivially simple. But the ...ker that designed the C/C++ notation and its blatant inconsistencies made it very difficult to follow in that language. For example, why is byte myVal = 5;  treated differently from byte myVal[1] = 5;

...R
Title: Re: "Pointers make my head spin" etc ...
Post by: AWOL on Jul 03, 2016, 10:05 am
For me the concept pointers (the addresses of memory locations at which data is stored) is trivially simple. But the ...ker that designed the C/C++ notation and its blatant inconsistencies made it very difficult to follow in that language. For example, why is byte myVal = 5;  treated differently from byte myVal[1] = 5;

...R
Because one is a scalar and the other a vector (albeit a very short one)?
Title: Re: "Pointers make my head spin" etc ...
Post by: Rupert909 on Jul 03, 2016, 10:57 am
For me the concept pointers (the addresses of memory locations at which data is stored) is trivially simple. But the ...ker that designed the C/C++ notation and its blatant inconsistencies made it very difficult to follow in that language. For example, why is byte myVal = 5;  treated differently from byte myVal[1] = 5;

...R
Just remember that array variables are poiinters. How hard is that? Assigning integer 5 to a pointer obviously is a dangerous thing to do.

:-)

Title: Re: "Pointers make my head spin" etc ...
Post by: pYro_65 on Jul 03, 2016, 01:56 pm
Just remember that array variables are poiinters. How hard is that? Assigning integer 5 to a pointer obviously is a dangerous thing to do.

:-)


You can treat them like pointers, however the reality is a little more complex.

An array is an array. An array id without a subscript can implicitly cast to a pointer, which points to the first element, but the array id is still an array.


Title: Re: "Pointers make my head spin" etc ...
Post by: Robin2 on Jul 03, 2016, 02:58 pm
Just remember that array variables are poiinters. How hard is that?
That part is easy. What I don't understand is why they (whoever "they" are) decided that a simple variable name should not also be a pointer. Under the hood they are both memory addresses. Why treat them differently?

...R
Title: Re: "Pointers make my head spin" etc ...
Post by: pYro_65 on Jul 03, 2016, 03:50 pm
That part is easy. What I don't understand is why they (whoever "they" are) decided that a simple variable name should not also be a pointer. Under the hood they are both memory addresses. Why treat them differently?

...R
Are you asking why "int a = 5;" isn't a pointer?
Title: Re: "Pointers make my head spin" etc ...
Post by: Robin2 on Jul 03, 2016, 07:23 pm
Are you asking why "int a = 5;" isn't a pointer?
To be precise I am asking if  int a[1] = 5; is treated as a pointer why is int a = 5; treated differently?

...R
Title: Re: "Pointers make my head spin" etc ...
Post by: pYro_65 on Jul 04, 2016, 06:51 am
int a[1] = 5;

The code above isn't valid. You need to use a brace-enclosed-initializer list.

But no, despite what @rupert909 mentioned, an array is not a pointer. It will cast to a pointer to the first element if used in an expression that accepts a pointer as an operand, however, it is most definitely an array and not a pointer.
Title: Re: "Pointers make my head spin" etc ...
Post by: westfw on Jul 04, 2016, 08:49 am
Pointers become obvious if you program in assembly language for a while.  (one of the reasons that some of us think that learning assembly language is still important, I guess!)

This is memory.  Memory consists of a bunch of boxes, each one with an address, and each one having some data as contents.

Code: [Select]
        Addr    Data
         0       123
         1        42
         2        19
         3         0
         4       255
         5        'C'
         6        'A'
         7        'T'


Defining a variable is equivalent to attaching a name (or "label") to a memory location to make it easier to refer to in your program.  Here, we have "answer = 42" and "char pet[] = "CAT";"  This all happens in the compiler; the actual runtime binary doesn't know anything about the labels or variable names.
Code: [Select]
Label   Addr    Data
         0       123
answer:  1        42
         2        19
p:       3         0
         4       255
pet:     5       'C'
         6       'A'
         7       'T'
8    0

we can make variable p be a pointer:  "byte *p = 0;"  Now, rather than having the value of a variable, p should have the ADDRESS of a variable.  By convention, a pointer initialized to 0 (aka "null") is one that doesn't point at anything.  But in the above you'll notice that 0 is actually a valid address (containing 123), so at the moment "*p" (read as "the contents at the pointer p" has 123, but address 0 isn't actually anything that we've made a variable, so that's probably some kind of error.
We can say "p=5;" or "p=pet;" or "p=&pet[0];" ("p gets the address of the first element of pet"), and then we have:
Code: [Select]

Label   Addr    Data
         0       123
answer:  1        42
         2        19
p:       3         5    ; points to pet
         4       255
pet:     5       'C'
         6       'A'
         7       'T'
8    0

Now, "*p" will be 'C'.  Note that there is nothing in the pointer to indicate exactly what it might be pointing at, or how long it is.  It could be pointing at a character 'C', or at the beginning of string "CAT", or at some numerical value that happens to be the same as the representation of the letter C (67)   The compiler tries to keep track of that for you, but again this disappears in the binary.
You can do math and stuff with the pointer.  If you add 1, it will now have the value of 6, which is pointing at "A" instead of "C".  You could subtract  2, and now it's pointing at itself (seems like a bad idea!)
You can pass p to a function, which would save space over passing all of "CAT".

And so on.  That's sort of the basics of pointers.  C has its own complications and niceities, like being able to point to things other than single bytes, or using array access syntax to access pointer values (and vis versa.)  But chunks of memory with addresses is where you start.
Title: Re: "Pointers make my head spin" etc ...
Post by: Robin2 on Jul 04, 2016, 09:53 am
int a[1] = 5;

The code above isn't valid. You need to use a brace-enclosed-initializer list.
Apologies for the inadvertent error in the syntax.

Quote
But no, despite what @rupert909 mentioned, an array is not a pointer. It will cast to a pointer to the first element if used in an expression that accepts a pointer as an operand, however, it is most definitely an array and not a pointer.
In that case it makes even less sense for the compiler not to also cast an ordinary variable name to a pointer when it is "used in an expression that accepts a pointer as an operand"

...R
Title: Re: "Pointers make my head spin" etc ...
Post by: pYro_65 on Jul 04, 2016, 03:04 pm
In that case it makes even less sense for the compiler not to also cast an ordinary variable name to a pointer when it is "used in an expression that accepts a pointer as an operand"
It is just a rule decided for that type and is explained in the section "standard conversions". I'll try my best to give it some sense though:

Quote
4.2 Array-to-pointer conversion [conv.array]
1 An lvalue or rvalue of type "array of N T" or "array of unknown bound of T" can be converted to a prvalue of type "pointer to T". The result is a pointer to the first element of the array.
An array is unrelated to 'ordinary' variables, and it has its own features just as primitive types have their own standard "integral conversions".

Similarly though, you can get a pointer to an array by using the address of operator (&). This gives you an actual "pointer to array", whereas the standard conversion only gives you a pointer to the first element (you can also create a reference to an array).


To make things a bit clearer, the standard conversion for arrays is needed to access array elements. This is because the subscripting operator works with pointers (not actually an array specific operator). It has a clause in its description mentioning this:

Quote
The expression E1[E2] is identical (by definition) to *((E1)+(E2))
Its identical form (second one listed above) shows that either E1 or E2 must be a pointer as it is dereferenced to access the value. You can also do a proof of this.

The code below is accessing the second element of the array two different ways using the subscripting operator, showing that at least one operand must be a pointer:

Code: [Select]
  int array[5];

  int a = array[1];

  int b = 1[array];


So even though an implicit array to pointer conversion may seem strange, it is in fact needed to access elements of arrays.

You might be wondering what use is an array that isn't converted to a pointer (which is why many consider arrays to be simply pointers). Well it is because arrays provide more information than a pointer. Size/length info is lost once you have a pointer. You can maintain this with an array reference or array pointer:

I used a typedef to make the syntax a bit easier on the eye.

Code: [Select]
typedef int ArrayType[5];

void setup() {

  ArrayType array = {1,2,3,4,5};

  AddOneToArray(array);
}

void AddOneToArray( ArrayType &array ){

  for( auto &element : array ){  //Size info is maintained
    element += 1;
  }
}

void loop() {}


You could use an ArrayType* as the function parameter, you'd just need to dereference the pointer to return to the actual array.

This next example is a little more complex and shows two things, returning an array (reference) from a function, and also an unrelated example showing a real array pointer.

Code: [Select]
typedef int ArrayType[5];

class MyArray{
  public:
 
    //Allows conversion of class type to internal array type (returns a reference to array)
    operator ArrayType&(){
      return data;
    }

  private:
    ArrayType data;
};

void setup() {

  MyArray foo;

  //Use conversion operator provided by class, then access an array element:
  foo[4] = 1;


  ArrayType bar = {1,2,3,4,5};
  //Take pointer to array
  ArrayType *ptr = &bar;

  //Do something with array pointer
  (*ptr)[4] = 2;

}

void loop() {}
Title: Re: "Pointers make my head spin" etc ...
Post by: Robin2 on Jul 04, 2016, 08:49 pm
 :smiley-sleep:    :smiley-sleep:    :smiley-sleep:   

...R
Title: Re: "Pointers make my head spin" etc ...
Post by: pYro_65 on Jul 05, 2016, 09:47 am
:smiley-sleep:    :smiley-sleep:    :smiley-sleep:   

...R
whatever
Title: Re: "Pointers make my head spin" etc ...
Post by: Naneen on Jul 07, 2016, 10:29 am
As some of you know I took a little time off to learn C++. We covered pointers and how they worked. After reading through these post I'm so confused.  Hey teach help!!!
Title: Re: "Pointers make my head spin" etc ...
Post by: pYro_65 on Jul 07, 2016, 12:10 pm
As some of you know I took a little time off to learn C++. We covered pointers and how they worked. After reading through these post I'm so confused.  Hey teach help!!!
What is confusing you?
Title: Re: "Pointers make my head spin" etc ...
Post by: Rupert909 on Jul 11, 2016, 10:55 pm
Code: [Select]
typedef int ArrayType[5];

void setup() {

  ArrayType array = {1,2,3,4,5};

  AddOneToArray(array);
}

void AddOneToArray( ArrayType &array ){

  for( auto &element : array ){  //Size info is maintained
    element += 1;
  }
}


Nice, didn't consider that array types remember their size, which they of course do (sizeof()).

Wasn't aware that C(++?) supports for-each type of loop syntax.

:-)

Title: Re: "Pointers make my head spin" etc ...
Post by: pYro_65 on Jul 12, 2016, 03:28 pm
Nice, didn't consider that array types remember their size, which they of course do (sizeof()).

Wasn't aware that C(++?) supports for-each type of loop syntax.
Yeah, maintaining the size info is useful, no need to force to a pointer, then pass a length anyway. But all depends on how it is used for what is best.

Ranged for loops were added in C++11.
Title: Re: "Pointers make my head spin" etc ...
Post by: chummer1010 on Jul 13, 2016, 02:35 am
Reading this thread made my head spin.
Title: Re: "Pointers make my head spin" etc ...
Post by: Robin2 on Jul 13, 2016, 10:21 am
an array is not a pointer. It will cast to a pointer to the first element if used in an expression that accepts a pointer as an operand,
I have not been explaining myself clearly enough.

I know that an array will cast to a pointer. What I don't understand is why a simple variable will not also cast to a pointer?

...R
Title: Re: "Pointers make my head spin" etc ...
Post by: Rupert909 on Jul 13, 2016, 11:37 am
I have not been explaining myself clearly enough.

I know that an array will cast to a pointer. What I don't understand is why a simple variable will not also cast to a pointer?

...R
I guess it was deemed too confusing.

Consider this example from Java, and you see what fun can arise from automatically handling Integer as object (pointer) and arithmetic value. The glory of "autoboxing" ...

Code: [Select]

// Integer is an object, but it can be assigned an int value. The compiler
// provides "autoboxing", which means the int is converted into an Integer
// with the given value

Integer a=1;
Integer b=1;
Integer c=2;

// (1)
if (a==b) {...} // pointer comparison - fails

// (1b)
if (a.intValue()==b.intValue()) {...}  // value comparison

// (2)
a=b; // pointer assignment

// (3)
a=b+3; // see below

// (4)
c++;




Example (3) shows auto(un)boxing in all its uglyness. Since the right hand side is an arithmethic expression, the reference to c is unboxed, becoming int value 1, the values are added, becoming 4, and the result is autoboxed into a new object of type Integer, with value 4.

So the code in (2) and (3) do radically different things.

Example (4) follows the logic of example (3). Integer objects are immutable, so here the value of the original Integer object referred by c, is unboxed, then incremented, then autoboxed into a new Integer object.

The boxed versions of primitive types in Java are good for exactly one thing, and that is that variables of these types can be set to null, which is handy in many situtations.

However, this gives rise to interesting runtime situations, since parameters to methods are also auto(un)boxed.

Code: [Select]

void myMethod (int x) {...}

Integer i=4;
myMethod(i); // ok

Integer j=null;
myMethod(j); // fails at runtime


The autoboxing feature lets programmers get away with inconsistencies between parameter declarations and actual parameter expressions, which work okay for non-null values.

:-)

Its a mess.



Title: Re: "Pointers make my head spin" etc ...
Post by: pYro_65 on Jul 13, 2016, 12:06 pm
I have not been explaining myself clearly enough.

I know that an array will cast to a pointer. What I don't understand is why a simple variable will not also cast to a pointer?

...R
Without trying to be rash, I explained this in the post you decided not to read.

If you do not want to read it all, start from the paragraph that starts with "To make things a bit clearer". It gives you the reasons why an array casts implicitly.
Title: Re: "Pointers make my head spin" etc ...
Post by: Robin2 on Jul 13, 2016, 01:21 pm
In spite of my smileys I did read your Reply.

I think the difference between us is that you are describing HOW C/C++ works whereas I am asking WHY does it work like that (because it seems to me to be inconsistent).

Another way that this "inconsistency" could be avoided would be if it was necessary to do an explicit cast to a pointer for an Array as well as for a simple variable.

(Don't lose sight of the fact that this is the Bar Sport section :) )

...R
Title: Re: "Pointers make my head spin" etc ...
Post by: Rupert909 on Jul 13, 2016, 01:46 pm
In spite of my smileys I did read your Reply.

I think the difference between us is that you are describing HOW C/C++ works whereas I am asking WHY does it work like that (because it seems to me to be inconsistent).

Another way that this "inconsistency" could be avoided would be if it was necessary to do an explicit cast to a pointer for an Array as well as for a simple variable.

(Don't lose sight of the fact that this is the Bar Sport section :) )

...R
Taking the address of an array returns a pointer to array (object), whereas the auto-conversion gives a pointer to the first element. Two functionalities can not be represented by a single implicit conversion, or explicit operator ('&').

Also, who said that the inventors of C, and later C++, were first and foremost concerned with internal consistency? With C being a step up from assembly, I'd think that terseness had high priority.

There's the old joke that the one regret Kernighan and Ritchie had about unix, was the "mail" command, should have been called "ml".

:-)
Title: Re: "Pointers make my head spin" etc ...
Post by: pYro_65 on Jul 13, 2016, 02:05 pm
In spite of my smileys I did read your Reply.

I think the difference between us is that you are describing HOW C/C++ works whereas I am asking WHY does it work like that (because it seems to me to be inconsistent).

Another way that this "inconsistency" could be avoided would be if it was necessary to do an explicit cast to a pointer for an Array as well as for a simple variable.
To mention it as an inconsistency, then to mention an explicit cast gives me reason to believe you did not understand my post.

I pointed out how C++ works, yes.

But I go on to use that to explain why arrays cast like that, so which ever way you want to describe it, I have covered it.

And to repeat very briefly, an array casts implicitly because it is the only way you can access elements (by using a pointer), so it makes sense to provide this implicitly.

...And why does an 'int' not do casting like this by default? Well that is because it does not make sense, is illogical, and is unrelated to an array.

You are asking why does an apple not taste like an orange, even though they are both fruit.

Fur is a trait of animals, a dog is an animal, but in no means does this imply that every animal is a dog, or every animal has fur...
Title: Re: "Pointers make my head spin" etc ...
Post by: Robin2 on Jul 13, 2016, 07:31 pm
Biology is full of inconsistencies because evolution has neither a plan nor foresight. There is no reason why human creations (such as programming languages) have to have them.

...R
Title: Re: "Pointers make my head spin" etc ...
Post by: pYro_65 on Jul 14, 2016, 02:30 am
Biology is full of inconsistencies because evolution has neither a plan nor foresight. There is no reason why human creations (such as programming languages) have to have them.

...R
There are no inconsistencies here. I'm confused as to why you trying so hard to connect two unrelated things.

Quote
Another way that this "inconsistency" could be avoided would be if it was necessary to do an explicit cast to a pointer for an Array as well as for a simple variable.
Write some pseudo code and see how your trail of thought does not really make sense. An array cast can not be applied to a 'simple' variable. For one, you need to use the address of operator to get the address of a variable. Casting it to a pointer gives you a pointer to somewhere, not a pointer to the variable.

Just rephrase your argument with another questionable statement: why can't I use the subscript operator with a simple variable ...Its inconsistent?

Well they may both be variables, but it'd be absurd to demand that a feature for arrays/pointers be available with things that have no use for them.

These aren't inconsistencies, its a flawed approach comparing two dissimilar things.

Two blueberry muffins, one with heaps of berries, and the other only has one. As the mixture was not mixed properly the muffins were inconsistent.

You cannot find an inconsistency between a brownie and a muffin, they are simply just different things. Saying your muffin is inconsistent because it does not look like a brownie is silly, but none the less, the same argument you are filing for arrays vs 'simple' variables.
Title: Re: "Pointers make my head spin" etc ...
Post by: Robin2 on Jul 14, 2016, 11:10 am
An array cast can not be applied to a 'simple' variable.
We are on different wavelengths.

Let's agree to disagree.

...R
Title: Re: "Pointers make my head spin" etc ...
Post by: pYro_65 on Jul 14, 2016, 02:35 pm
We are on different wavelengths.

Let's agree to disagree.
Nah, nothing is learned that way.

I was hoping you'd pick it up, but if you are really determined to argue that it is wrong for a simple variable to not be converted to a pointer, then you can stop looking at arrays, and focus on pointer arithmetic. Then you'll see how your argument is invalid.

Quote
I know that an array will cast to a pointer. What I don't understand is why a simple variable will not also cast to a pointer?
...
it makes even less sense for the compiler not to also cast an ordinary variable name to a pointer when it is "used in an expression that accepts a pointer as an operand"
This doesn't work like an int array would, no implicit cast (and really why should there be, it doesn't make sense).

int i = 4;
int *ptr = i;


But use an int in pointer arithmetic... and, well, the result is a pointer!

int i;
int *ptr;

int *ptr2 = ptr + i;


None the less, an integer cannot cast to a pointer implicitly when used in the circumstances an array can be used, but this is due to them being completely different things (apples/oranges).

Simple! No wires crossed, different wavelengths, or language barriers, just pure analysis of the facts.

Title: Re: "Pointers make my head spin" etc ...
Post by: Robin2 on Jul 14, 2016, 06:48 pm
I am coming at this from a very basic position. Have a look at this snippet (I hope my syntax is correct)

Code: [Select]
byte myArray[1];
myArray[0] = 5;

byte myVar = 5;

 
In both cases there is a memory location at an address and it contains the number 5.

If I want to use this function call (https://tmrh20.github.io/RF24/classRF24.html#a4cd4c198a47704db20b6b5cf0731cd58)
bool RF24::write( const void * buf, uint8_t len)
I can do it like this
Code: [Select]
myRF24.write(myArray, 1);
or
Code: [Select]
myRF24.write(&myVar, 1);
(again I hope I have the syntax correct - I have only used the other version)

I cannot for the life of me see why C/C++ was designed in such a way that these things need to be treated differently.

...R
Title: Re: "Pointers make my head spin" etc ...
Post by: Whandall on Jul 14, 2016, 07:14 pm
I can do it like this
Code: [Select]
myRF24.write(myArray, 1);
or
Code: [Select]
myRF24.write(&myVar, 1);
(again I hope I have the syntax correct - I have only used the other version)

I cannot for the life of me see why C/C++ was designed in such a way that these things need to be treated differently.
I think it is treated the same way, because
Code: [Select]
myRF24.write(myArray, 1);is only a shortcut for
Code: [Select]
myRF24.write(&myArray[0], 1);
Title: Re: "Pointers make my head spin" etc ...
Post by: Robin2 on Jul 14, 2016, 11:03 pm
I think it is treated the same way, because
Code: [Select]
myRF24.write(myArray, 1);is only a shortcut for
Code: [Select]
myRF24.write(&myArray[0], 1);
OK. Then my question is why didn't they make it so that the same shortcut works with the simple variable myVar? (i.e. so the & is not needed)

...R
Title: Re: "Pointers make my head spin" etc ...
Post by: Whandall on Jul 14, 2016, 11:30 pm
There is no shortcut in the myVar case, because there is no myVar[0].
Title: Re: "Pointers make my head spin" etc ...
Post by: pYro_65 on Jul 15, 2016, 07:05 am
OK. Then my question is why didn't they make it so that the same shortcut works with the simple variable myVar? (i.e. so the & is not needed)
This has been covered fairly extensively above, but to summarize:

Quote
the standard conversion for arrays is needed to access array elements. This is because the subscripting operator works with pointers (not actually an array specific operator)

Quote
The expression E1[E2] is identical (by definition) to *((E1)+(E2))
Its identical form (second one listed above) shows that either E1 or E2 must be a pointer as it is dereferenced to access the value.

The code below is accessing the second element of the array two different ways using the subscripting operator, showing that at least one operand must be a pointer:


Code: [Select]
int array[5];

  int a = array[1];

  int b = 1[array];


So even though an implicit array to pointer conversion may seem strange, it is in fact needed to access elements of arrays.
...
An array is unrelated to 'ordinary' variables, and it has its own features just as primitive types have their own standard "integral conversions".
...
And why does an 'int' not do casting like this by default? Well that is because it does not make sense, is illogical, and is unrelated to an array.
...
There are no inconsistencies here. I'm confused as to why you trying so hard to connect two unrelated things.
...
These aren't inconsistencies, its a flawed approach comparing two dissimilar things.
And one more to the pile from Whandall:

Quote
There is no shortcut in the myVar case, because there is no myVar[0].
So as you can see, there is no array logic in 'simple' variables, because they aren't arrays. The array functionality is there because it is required, as I have mentioned above.

Your shortcut that you cannot understand why it isn't available to a standard variable makes no sense, why, because the choice is ambiguous: Do you return a pointer, or the actual int. With an array id (without subscript) all you have is a pointer to the first element, as an array reference and array pointer are not compatible and ignored.

Title: Re: "Pointers make my head spin" etc ...
Post by: Robin2 on Jul 15, 2016, 09:40 am
Your shortcut that you cannot understand why it isn't available to a standard variable makes no sense, why, because the choice is ambiguous: Do you return a pointer, or the actual int. With an array id (without subscript) all you have is a pointer to the first element, as an array reference and array pointer are not compatible and ignored.
Thanks.

That makes some sense.

It has taken a long time :) :)

...R
Title: Re: "Pointers make my head spin" etc ...
Post by: pYro_65 on Jul 15, 2016, 12:59 pm
Thanks.

That makes some sense.

It has taken a long time :) :)

...R
lol, glad to be of service.
Title: Re: "Pointers make my head spin" etc ...
Post by: Robin2 on Jul 15, 2016, 11:31 pm
On further reflection I think I still have the same problem.

Based on your explanation I can understand why there is a need to use &myVar so as to make it clear that it is the address that is needed rather than the value.

However if the system was consistent you would also be required to use &myArray when you want the address of the array. Using myArray with neither an & nor a subscript should cause an error.

(Keep in mind that this is a language that prides itself on being pernickety)

...R
Title: Re: "Pointers make my head spin" etc ...
Post by: pYro_65 on Jul 16, 2016, 04:28 am
However if the system was consistent you would also be required to use &myArray when you want the address of the array. Using myArray with neither an & nor a subscript should cause an error.
That is how you get an address of an array!

But that is the problem, it is a pointer to an array not a pointer to the first element. If you used a subscript operator like (&myArray)[3] you are attempting to access an array of arrays. Each index moves the pointer the length of the entire array - and is valid in some circumstances (multidimensional arrays).

The biggest point to mention here is 'myArray' is not returning a pointer to the variable, but an element - a closed concept only for arrays. '&myArray' and '&myInt' are both returning pointers to the variable you are using. Which is consistent use of the address-of operator.

If you dereference the pointer returned by '&myArray' and '&myInt' you return to the original variable. Whereas dereferencing the pointer provided by 'myArray' you get a reference to an element, which has nothing to do with the array.

If the rules you mentioned were in place, there would be no way to access the elements of a variable without some ugly code which converts the array pointer to a primitive pointer, then using pointer arithmetic to move along raw bytes.

((char*)(&myArray))[ 4 ];

This method is quite ugly, and breaks the strict typing elements. It allows you to completely disregard the type of the array, and has no size information associated with it. The array might not even be a char type.

And as for consistency, the way array's are accessed in C++ is consistent with 90% of other languages that use arrays. The parts that differ are because C++ has the concept of pointers, which many languages do not.

Another point is in reality, 'myArray' and 'myInt' are both expressions returning a reference to themselves. I think what you were saying is inconsistent, is actually there, it is just not as obvious. The code below shows this:

Code: [Select]
  int array[10];
  int (&arrRef)[10] = array;

  int value;
  int &valRef = value;


The reason why an array can cast is because it has a built in conversion. This concept can be described with a struct:

The code below will not work because a pointer and object are not compatible.

Code: [Select]
struct Foo{
  char *ptr;
};

void setup() {

  Foo foo;
  char *ptr = foo;
}

void loop(){}


However adding a conversion operator, like what arrays have built in, then it can:

Code: [Select]
struct Foo{
  //Conversion operator
  operator char*(){ return ptr; }
  char *ptr;
};

void setup() {

  Foo foo;
  char *ptr = foo;
}

void loop(){}


Title: Re: "Pointers make my head spin" etc ...
Post by: Robin2 on Jul 16, 2016, 09:44 am
And, after a good night's sleep I am less convinced of the logic in the piece I quoted in Reply #40.

I don't really see why the choice would be ambiguous - why would I want the address of a simple variable? If it is a simple variable just assume I want the value.

There could be a special "add on" for those folks who really do want the address of a simple variable.

...R
Title: Re: "Pointers make my head spin" etc ...
Post by: pYro_65 on Jul 16, 2016, 10:38 am
I don't really see why the choice would be ambiguous - why would I want the address of a simple variable? If it is a simple variable just assume I want the value.
Exactly! That is what happens now.


You were originally asking:

Quote
I know that an array will cast to a pointer. What I don't understand is why a simple variable will not also cast to a pointer?
You have answered this yourself: "why would I want the address of a simple variable? If it is a simple variable just assume I want the value.".

And if you checkout the two lines above the first code box in my last post, you'll see that this behavior is consistent!
------------------------------------
The ambiguity I mentioned would happen if a variable could return a value, or pointer when used in a pointer expression. This is because a pointer and a pointer can be added together (pointer arithmetic), but a pointer and an integral type can also be added together - so if the conversion you proposed was introduced, which one do you use... the pointer or value?

This is not the case with an array as only the pointer conversion is compatible. An array type cannot be cast to any other type except a reference to its own type. The ambiguity appears when there are two or more conversions which are compatible with the type being converted to (C++ is allowed to implicitly cast once for anything if there is an appropriate conversion available).
Title: Re: "Pointers make my head spin" etc ...
Post by: Robin2 on Jul 16, 2016, 12:52 pm
See Reply #33   :)

We have wasted enough bandwith and server storage on this.

...R
Title: Re: "Pointers make my head spin" etc ...
Post by: pYro_65 on Jul 16, 2016, 01:32 pm
See Reply #33   :)

We have wasted enough bandwith and server storage on this.

...R
Hmmm, it doesn't seem like you really know what you are trying to explain.

Why don't you do a big favor and justify these two statements you have made, then possibly your other wavelength may come to light:

Quote
I know that an array will cast to a pointer. What I don't understand is why a simple variable will not also cast to a pointer?
and

Quote
why would I want the address of a simple variable? If it is a simple variable just assume I want the value.
?????? Seriously what is going on, I'm quite intrigued!


All of your posts repeat the same thing over and over, then you answer your own question. If you wrote the wrong thing, this isn't a different wavelength, it is bad communication.

Why don't you try and explain what your gripe is in more than two sentences.
Or if you are waiting for people to simply agree with you, regardless of how many logical explanations are put forward, then you are simply just trolling (in which case you don't really agree with what you are writing).

Don't worry about bandwidth, the forum admin certainly don't, did you know that an open forum page checks for new alerts every 10 seconds. Multiply this by everyone online, and a few posts really are insignificant.

I would really like to know what the hidden meaning is in your quotes:

Quote
However if the system was consistent you would also be required to use &myArray when you want the address of the array. Using myArray with neither an & nor a subscript should cause an error.
Answered here (http://forum.arduino.cc/index.php?topic=410528.msg2843143#msg2843143)

Quote
OK. Then my question is why didn't they make it so that the same shortcut works with the simple variable myVar? (i.e. so the & is not needed)
Answered here (http://forum.arduino.cc/index.php?topic=410528.msg2840946#msg2840946) & here (http://forum.arduino.cc/index.php?topic=410528.msg2841639#msg2841639) & here (http://forum.arduino.cc/index.php?topic=410528.msg2843350#msg2843350)

Quote
I know that an array will cast to a pointer. What I don't understand is why a simple variable will not also cast to a pointer?
...
it makes even less sense for the compiler not to also cast an ordinary variable name to a pointer when it is "used in an expression that accepts a pointer as an operand"
Answered here (http://forum.arduino.cc/index.php?topic=410528.msg2840946#msg2840946) & here (http://forum.arduino.cc/index.php?topic=410528.msg2843350#msg2843350) & here (http://here) & by yourself

Quote
I think the difference between us is that you are describing HOW C/C++ works whereas I am asking WHY does it work like that (because it seems to me to be inconsistent).

Another way that this "inconsistency" could be avoided would be if it was necessary to do an explicit cast to a pointer for an Array as well as for a simple variable.
And this is answered in pretty much every post in response to your questions. The reasons explaining this contain both how C++ works and why it works this way. I have also explained the consequences of why it wouldn't work if things were how you'd prefer.

Simply, what you would like to see, you yourself have given a reason as to why adding the functionality you would like is silly regardless of how consistent you think it could be.  And I have given compelling evidence as to why things wouldn't work if we removed what you don't like.

Title: Re: "Pointers make my head spin" etc ...
Post by: Robin2 on Jul 16, 2016, 03:09 pm
To go back to the title - my head is spinning  :)  :)

...R
Title: Re: "Pointers make my head spin" etc ...
Post by: pYro_65 on Jul 16, 2016, 03:14 pm
To go back to the title - my head is spinning  :)  :)

...R
It sure is. When you get yourself straightened out, feel free to join an intelligent discussion.

Avoiding the question I asked at the top of my last post is credible evidence you are just trolling, and have been caught out in it by answering your own irrationality.
Title: Re: "Pointers make my head spin" etc ...
Post by: Robin2 on Jul 16, 2016, 06:22 pm
See my comment at the bottom of Reply #28.

...R
Title: Re: "Pointers make my head spin" etc ...
Post by: Rupert909 on Jul 16, 2016, 10:35 pm
Oh children ... behave now! :-)
Title: Re: "Pointers make my head spin" etc ...
Post by: AWOL on Jul 16, 2016, 10:37 pm
Amen.
Title: Re: "Pointers make my head spin" etc ...
Post by: Robin2 on Jul 17, 2016, 09:38 am
I am waiting for the sun to emerge from the mist - it is forecast to appear soon.

Let me try to re-present my question.

In Reply #35  I said
Quote
If I want to use this function call
bool RF24::write( const void * buf, uint8_t len)
I can do it like this
Code: [Select]
myRF24.write(myArray, 1);
or
Code: [Select]
myRF24.write(&myVar, 1);
Would it be possible to have written the C/C++ compiler so that these would both work
Code: [Select]
myRF24.write(myArray, 1);
or
Code: [Select]
myRF24.write(myVar, 1);

...R
Title: Re: "Pointers make my head spin" etc ...
Post by: GoForSmoke on Jul 21, 2016, 09:27 pm
I learned Forth before I learned C, which has pointers and is less complicated than C++ so it's been easier for me. Forth uses addresses without extra packaging.

int x;

int y[] = { 0,1,2,3,4 };

The difference between x and y is that x is a variable and y is an array of variables.
They shouldn't be treated the same.

int z = 7;

z += x;
z += y; // trying to treat array y the same as variable x, should z now == 17?

However I can treat x and y[0] pretty much the same which makes sense since both are ints.

x = 4;
y[0] = 4;

To stop the spinning I think that the spinners should learn how memory works, what addresses are and then proceed to how they are used in whatever language has them spinning.

Most confusion is due to either unknown or misunderstood knowledge. First thing to do is to clarify your understanding. I live in a country where so many people consider their ignorance as some kind of sacred, I see the need for clarity all around me every day.
Title: Re: "Pointers make my head spin" etc ...
Post by: Robin2 on Jul 21, 2016, 09:33 pm
Reply #54 does not deal with the question I posed in Reply #53

I am not asking for an explanation of how the language works. Rather I am asking could one aspect of it have been done differently if the original designers had been minded to?

As far as I can see the compiler will be perfectly well aware that myVar is a simple variable and could make the reasonable assumption that I am only interested in the value at that memory location.

...R
Title: Re: "Pointers make my head spin" etc ...
Post by: GoForSmoke on Jul 21, 2016, 09:41 pm
Perhaps you need caffeine or new glasses.

Quote
The difference between x and y is that x is a variable and y is an array of variables.
They shouldn't be treated the same.[\quote]

is not "how the language works".

Title: Re: "Pointers make my head spin" etc ...
Post by: Robin2 on Jul 22, 2016, 10:08 am
Perhaps you need caffeine or new glasses.
Some of us like to wonder what might be beyond the hills.

Others are content to stay in the valley :)

...R