Author Topic: [C] Pointers - what is the point?  (Read 25365 times)

0 Members and 1 Guest are viewing this topic.

Offline jpanhalt

  • Super Contributor
  • ***
  • Posts: 3395
  • Country: us
Re: [C] Pointers - what is the point?
« Reply #50 on: July 17, 2018, 10:19:07 am »
but if i am pointing at another variable why not just use the variable?

I think you answered your own question.  Pointers keep track of where or what that variable is.

Sorry to come late to the party, but I do disagree with those who say pointers are almost useless for mid-range chips (specifically Microchip PIC devices).  Indirect addressing was introduced early on by Microchip with its FSR registers.  Current chips can access the entire range of program and RAM memory with them.  They are quite useful.   Microchip has seen that and introduced multiple FSRn's in its newest chips as well as instructions such as 'moviw' and 'movwi' with auto increment and decrement to facilitate use.  Moreover, if you run out of FSR's, you can create your own.   That can be used, for example in FIFO ring buffers where you may not want to tie up the FSR's.
 

Online Mechatrommer

  • Super Contributor
  • ***
  • Posts: 11535
  • Country: my
  • reassessing directives...
Re: [C] Pointers - what is the point?
« Reply #51 on: July 17, 2018, 10:26:06 am »
...as well as instructions such as 'moviw' and 'movwi' with auto increment and decrement to facilitate use....
people who understand this, used it, get acquainted with it... will swear by the pointer and why they are necessary in some critical performance application. btw, pointer will enable the program logic to control many variables from only one variable (pointer) well isnt that confusing? :-DD
Nature: Evolution and the Illusion of Randomness (Stephen L. Talbott): Its now indisputable that... organisms “expertise” contextualizes its genome, and its nonsense to say that these powers are under the control of the genome being contextualized - Barbara McClintock
 

Online brucehoult

  • Super Contributor
  • ***
  • Posts: 3997
  • Country: nz
Re: [C] Pointers - what is the point?
« Reply #52 on: July 17, 2018, 10:26:41 am »
If you consider a microcontroller that responds asynchronously to multiple requests -- say, reading digital temperature sensors, setting the duty cycle of some PWM outputs, and such --, a queue of such commands or requests makes a lot of sense. If you need different requests to have different priorities, you can implement that too with a binary heap, quite effectively.

Point of order!

A heap doesn't require any embedded pointers at all. You only need an array to store the maximum number of elements, the address of the array, and a count of how many elements are currently present (or a pointer to the first free element).

If a node is at offset N from the start of the heap (zero based), then its children are at offsets 2N+1 and 2N+2, if those nodes are not >= the limit pointer.
 
« Last Edit: July 17, 2018, 11:19:05 am by brucehoult »
 

Offline bd139

  • Super Contributor
  • ***
  • Posts: 23017
  • Country: gb
Re: [C] Pointers - what is the point?
« Reply #53 on: July 17, 2018, 10:26:55 am »
This whole thread reminds me why we should teach computing from the bottom up.
 
The following users thanked this post: mathsquid, GeorgeOfTheJungle, newbrain, rrinker, JPortici, bsudbrink

Online SimonTopic starter

  • Global Moderator
  • *****
  • Posts: 17728
  • Country: gb
  • Did that just blow up? No? might work after all !!
    • Simon's Electronics
Re: [C] Pointers - what is the point?
« Reply #54 on: July 17, 2018, 11:46:59 am »
The book is not MCU oriented, and will not help with IDE settings..
there is the love to programming, there is the love to completing a project in due time. we know he's been in a serious professional business industry and been programing for a while but keep asking fundamental things recently, and complained how his sources are not for embedded programming he loved to. so i suspect he's into "learn if needed" basis. i have "C++ Nuts & Bolts: For Experienced Programmers" book. dont get scared by the term "Experienced" its not, the right term should be replaced with "Complete Guide", its the one i will grab if i forgot or got confused by the C/C++ syntaxes. its less than an inch thick, i think if i'm zero, i can complete the self-learnt course using the book alone in a month or so (and i have 5 childrens :P)...

only drawbacks is it lacks of practical and complete working examples let alone embedded, just examples needed to demonstrate the usage of each C/C++ keywords and syntaxes, from the basic pointers and arrays to the witchery of polymorphism, so we need some imagination there. the 2nd drawback is its heavily C++ oriented programming style with alot of "cout <<" that i hate, so you need to familiarize with C coding style and then differentiate which is C++ specific that cant be used in C style. if i'm like Simon i think i wont have trouble since i already have some basic experience programming C. fwiw.


Serious? I'm never sure how serious my employer is but yes I tend to learn as I go. My experience so far is limited and has made minimal use of the cleverer things.
 

Online Mechatrommer

  • Super Contributor
  • ***
  • Posts: 11535
  • Country: my
  • reassessing directives...
Re: [C] Pointers - what is the point?
« Reply #55 on: July 17, 2018, 01:00:18 pm »
serious i mean military, if i recall correctly you involved in some military vehicle project, no?
Nature: Evolution and the Illusion of Randomness (Stephen L. Talbott): Its now indisputable that... organisms “expertise” contextualizes its genome, and its nonsense to say that these powers are under the control of the genome being contextualized - Barbara McClintock
 

Offline NivagSwerdna

  • Super Contributor
  • ***
  • Posts: 2495
  • Country: gb
Re: [C] Pointers - what is the point?
« Reply #56 on: July 17, 2018, 01:38:05 pm »
I am completely confused, pointers are just another name for some variable, I have read a couple of explanations and I'm still not getting why I would want to use them  :horse:.
I love these questions because everyone has an answer.  :)

You don't need to know about pointers you can let the magic happen.

int fred[10];

fred[0] = 123;   // Works

i = fred[0]; /// works

i = fred[j]; // works

That all works fine.  You can ignore any videos, ignore any books etc.

However one day you might be interested in passing a reference to one of the elements to a function rather than the whole array.... you could pass the whole array and an index or could pass a reference to the single element... e.g. &fred[2]

& gives you the address of the location of element fred[2].  Given an address you can get to the value by using *

So

int* interesting = &fred[2];
*interesting = 567;

is equivalent to fred[2] = 567

Now in C there are a few syntactic sugars in operation so... fred is actually short-hand for &fred[0] i.e. the address of the 0-th element of fred
Also at compile time the type of elements of an array is known so fred+3 takes into account the size of the fred elements.  i.e fred+3 and &fred[3] are equivalent.

Likewise pointer arithmetic works so...
int* interesting = &fred[2];
interesting++;
*interesting = 321;

sets the value of &fred[3]

Once you know the & and * operators you can apply them to anything.  So for example you can have a pointer to a function and then call it
(*fn)(args), which is useful for looking up functions at runtime... e.g. FSM implementations.

The underlying processor will be either using a pointer (the address) to a memory location or an internal register to hold a value. Machine operations for indirection using a register as an address are common place and efficient.

They are also dogs.... and a particularly cool, inbound aircraft warning system, one is described here... https://en.wikipedia.org/wiki/Judy_(dog)
 

Online Nominal Animal

  • Super Contributor
  • ***
  • Posts: 6171
  • Country: fi
    • My home page and email address
Re: [C] Pointers - what is the point?
« Reply #57 on: July 17, 2018, 03:08:00 pm »
A heap doesn't require any embedded pointers at all.
No, I meant with a queue or a binary heap where the nodes are of different types and sizes, similar to the stack structures in my example.  I take it you didn't read my previous post in this thread...  :'(

To reword: Consider a microcontroller with various peripherals, connected to a computer, where some of the peripherals take a while to read/set. Rather than block for every single command/request, you can implement a priority queue using a binary heap, with each request or command being a separate node. These nodes can be statically allocated, typically 2 or 3 per type, depending on the peripherals configured.  One part receives incoming commands/requests, parses them, and adds to the queue. Another part of the code responds when commands/requests are fulfilled. Third part of the code decides which command/request to act upon next.

Such an approach is especially nice on microcontrollers with native USB interfaces, because the transfers are inherently asynchronous.  A lot of the serial port daemons I've seen don't really handle asynchronous communication, but expect to be able to write-then-read, one command/request at a time.  Which is fine if the round-trip time is short or you don't have many sensors.  When you do have many sensors or sensors that take a long time to respond, more complicated code is warranted; and that is the point where one finds algorithms and approaches where pointers are very useful, methinks.
 

Offline Maxlor

  • Frequent Contributor
  • **
  • Posts: 565
  • Country: ch
Re: [C] Pointers - what is the point?
« Reply #58 on: July 17, 2018, 03:30:24 pm »
When I learned programming a long time ago, I had a hard time wrapping my head around it. I thought I had gotten it, but got floundered later when having to do ** instead of just *, or wondered it is & instead of *, shouldn't the compiler know this is a pointer, yaddayadda, in other words, my understanding was not robust at all.

I then focused on x86 assembly. When I learned about how indirect adressing (with optional indexing) works, it finally clicked 100% for me, because at that point, all the abstractions and complexity had all been peeled away and I got to see what the CPU is actually doing. Maybe this learning approach works for you too.

(Note that the simple microcontrollers that one'd commonly program in ASM, say an 8-bit PIC, do not have the advanced addressing modes of the x86 architecture, so looking at those is not a substitute here.)
 

Offline NivagSwerdna

  • Super Contributor
  • ***
  • Posts: 2495
  • Country: gb
Re: [C] Pointers - what is the point?
« Reply #59 on: July 17, 2018, 03:45:30 pm »
(Note that the simple microcontrollers that one'd commonly program in ASM, say an 8-bit PIC, do not have the advanced addressing modes...)
Indirect Addressing: INDF and FSR
 

Offline newbrain

  • Super Contributor
  • ***
  • Posts: 1714
  • Country: se
Re: [C] Pointers - what is the point?
« Reply #60 on: July 17, 2018, 03:47:52 pm »
(Note that the simple microcontrollers that one'd commonly program in ASM, say an 8-bit PIC, do not have the advanced addressing modes of the x86 architecture, so looking at those is not a substitute here.)
Ah, the good old days when 8 bitters had about as many addressing modes as address bus pins... :blah:
Nandemo wa shiranai wa yo, shitteru koto dake.
 

Offline NivagSwerdna

  • Super Contributor
  • ***
  • Posts: 2495
  • Country: gb
Re: [C] Pointers - what is the point?
« Reply #61 on: July 17, 2018, 04:01:02 pm »
(Note that the simple microcontrollers that one'd commonly program in ASM, say an 8-bit PIC, do not have the advanced addressing modes of the x86 architecture, so looking at those is not a substitute here.)
Ah, the good old days when 8 bitters had about as many addressing modes as address bus pins... :blah:
Indeed. http://www.obelisk.me.uk/6502/addressing.html
 

Offline bd139

  • Super Contributor
  • ***
  • Posts: 23017
  • Country: gb
Re: [C] Pointers - what is the point?
« Reply #62 on: July 17, 2018, 05:12:31 pm »
Zero page on the 6502 was awesome. Made me think of the CPU as a RISC processor with 256 memory mapped registers :)
 
The following users thanked this post: GeorgeOfTheJungle, newbrain

Online westfw

  • Super Contributor
  • ***
  • Posts: 4196
  • Country: us
Re: [C] Pointers - what is the point?
« Reply #63 on: July 18, 2018, 10:46:02 pm »
Quote
    if you dont know whats its for, you dont need it.

Unfortunately, for C you end up needing to know something about pointers in order to be able to do anything with "strings."

Quote
    especially important for Embedded systems and other resource-limited environments:
    Dereferencing pointers to access the memory that's being pointed to takes more time than directly using the variable.

Um, that's not necessarily true.ARM in particular is really horrible at "directly accessing variables."On AVR, an "LD r1,Z+offset" instruction is the same speed and half the size of "LDS r1,variable"Even on an 8bit PIC, there significant advantages and no speed penalty for accessing memory via the INDFn registers (no Bank select register when trying to use data structures that span banks, as a biggie.)
(this supposes that the pointer itself is already set up, which a compiler should be doing efficiently.  But consider a sequence like:

Code: [Select]
// AVR code to initialize UART
UBRR0L = somediv;   // 3 words for each setting...
UBRR0H = highdiv;
UCSR0C = someval;
UCSR0B = someval2;
UCSR0A = someval3;
// 15 words total.
vs
Code: [Select]
uartp = &UART0;    // two words to initialize pointer
uartp->UBRRL = somediv;   // two words for each setting
uartp->UBRRH = highdiv;
uartp->UCSRC = someval;
uartp->UCSRB = someval2;
uartp->UCSRA = someval3;
// 12 words total.
« Last Edit: July 18, 2018, 11:50:16 pm by westfw »
 

Offline GeorgeOfTheJungle

  • Super Contributor
  • ***
  • !
  • Posts: 2699
  • Country: tr
Re: [C] Pointers - what is the point?
« Reply #64 on: July 18, 2018, 11:00:42 pm »
Page zero indexed indirect FTW.
The further a society drifts from truth, the more it will hate those who speak it.
 

Offline GeorgeOfTheJungle

  • Super Contributor
  • ***
  • !
  • Posts: 2699
  • Country: tr
Re: [C] Pointers - what is the point?
« Reply #65 on: July 18, 2018, 11:25:23 pm »
I am completely confused, pointers are just another name for some variable, I have read a couple of explanations and I'm still not getting why I would want to use them  :horse:.

*p is "another name" for a, but the pointer p is the address where a is stored, this:

Code: [Select]
#include <stdio.h>
int b= 66;
int main (void) {
    int a= 27;
    int* p= &a;
    printf(" a: %d\n",a);
    printf("*p: %d\n",*p);
    printf(" p: %p\n",p);
    printf("&a: %p\n",&a);
    p= &b;
    printf(" b: %d\n",b);
    printf("*p: %d\n",*p);
    printf(" p: %p\n",p);
    printf("&b: %p\n",&b);
    return 0;
}

Gives:

Code: [Select]

 a: 27
*p: 27
 p: 0x7fff5fbff8b4
&a: 0x7fff5fbff8b4
 b: 66
*p: 66
 p: 0x100001068
&b: 0x100001068
« Last Edit: July 20, 2018, 07:40:26 am by GeorgeOfTheJungle »
The further a society drifts from truth, the more it will hate those who speak it.
 

Online brucehoult

  • Super Contributor
  • ***
  • Posts: 3997
  • Country: nz
Re: [C] Pointers - what is the point?
« Reply #66 on: July 19, 2018, 12:21:28 am »
Zero page on the 6502 was awesome. Made me think of the CPU as a RISC processor with 256 memory mapped registers :)

Except the code density and speed sucked! Something as simple as adding or subtracting two 16-bit variables stored in ZP took 13 bytes of code (clc; lda $a; adc $b; sta $c; lda $a1+1; adc $b+1; sta $c+1) and 20 clock cycles. Compare that to 2-4 bytes of code and one clock cycle for variables stored in registers on anything from AVR to ARM to RISC-V to 68040/80486 or newer.

It's no wonder bytecode interpreters or threaded-code were so popular on those machines. Speed was even worse, but at least you could fit a decent amount of code into memory. Even Woz's ancient SWEET16 got that down to 3 bytes of code, and it integrated nicely with native code too.

 

Offline GeorgeOfTheJungle

  • Super Contributor
  • ***
  • !
  • Posts: 2699
  • Country: tr
Re: [C] Pointers - what is the point?
« Reply #67 on: July 19, 2018, 12:26:54 am »
If at least X and Y had been 16 bits ...
The further a society drifts from truth, the more it will hate those who speak it.
 

Offline rhb

  • Super Contributor
  • ***
  • Posts: 3476
  • Country: us
Re: [C] Pointers - what is the point?
« Reply #68 on: July 19, 2018, 01:40:39 am »
I had to work on a FORTRAN internal read code which allowed user defined data formats.  Once the first record had been read, the format was fixed.  But doing it in FORTRAN required repeating all the conditional tests.

I wrote a C routine which constructed a table of pointers to the appropriate FORTRAN internal read function, the input buffer and the output buffer the first time it was called.  After the first call the function pointers were no longer null.  So instead of populating the table it simply executed the functions in the table until it hit a null function pointer.  This gave a 6x improvement in performance.  When you're processing ASCII files with several million records on an early 1990's computer, that's a very big improvement. Instead of waiting an hour, you had the result in 10 minutes.  A good excuse for a coffee break.

Get a copy of:

Expert C Programming: Deep C Secrets
Peter Van Der Linden
Prentice-Hall 1994

I think the best way to understand pointers is to study assembly, preferably on something like the 6502 or 6809.  Though the STM32 series and the MSP430 series will also do and are more readily available.

C is just barely above assembly language.  It's fundamentally a portable assembly language.  It separates the mental constructs from the implementation details. More recent versions of the standard have muddied that, but if you read K&R and the "Unix Programming Environment" by Kernighan and Pike it will become much more clear.  If yuo read the two volume set of Bell Labs Journal articles about Unix a lot of things will become obvious.

It's the same thing with esoterica such as caches and why certain memory access patterns have really bad performance that a minor change can speed up tremendously

The history of computing is actually very important to any work being done today.  I have seen the same mistakes repeated every 8-10 years.  it's really sad as a little understanding of history would prevent them.

Read "The Story of Mel", a Usenet posting by Ed Nather about Mel Kaye.  "Pointers?  We don't need no stinking pointers!  We know how the machine works."
 

Online brucehoult

  • Super Contributor
  • ***
  • Posts: 3997
  • Country: nz
Re: [C] Pointers - what is the point?
« Reply #69 on: July 19, 2018, 01:48:33 am »
If at least X and Y had been 16 bits ...

Like .. what was that chip the same people did at another company earlier? The company that sued them to stop making the socket-compatible 6501. Yeah. It had 16 bit X register and SP. And *two* accumulators. But no Y. Very similar instruction set.

Probably a superior chip if it hadn't been EIGHT times more expensive.
 

Offline GeorgeOfTheJungle

  • Super Contributor
  • ***
  • !
  • Posts: 2699
  • Country: tr
Re: [C] Pointers - what is the point?
« Reply #70 on: July 19, 2018, 01:53:37 am »
The motorola 6800 you mean?
The further a society drifts from truth, the more it will hate those who speak it.
 

Online brucehoult

  • Super Contributor
  • ***
  • Posts: 3997
  • Country: nz
Re: [C] Pointers - what is the point?
« Reply #71 on: July 19, 2018, 02:21:52 am »
I think the best way to understand pointers is to study assembly, preferably on something like the 6502 or 6809.  Though the STM32 series and the MSP430 series will also do and are more readily available.

Agreed on the assembly language, but those chips are just needlessly like wrestling with an octopus these days .. as are the 8080/Z80/8088. The 6809 and 8088 less so than the others (and in fact they are remarkably similar to each other, once you get past Intel's ridiculous assembly language).

These days I'd recommend using one of the following, on linux -- native if available but otherwise a cross compiler/assembler, decent emulator (e.g. qemu), and binfmt_misc works great to let you write real, useful, programs that work as if they were native on your computer (just slower).

- AVR pretty great except for only having two registers that can dereference pointers, and of course more work to use 16 or 32 bit values.

- ARMv2 - ARMv4. Great except overly complex addressing modes, shifted 2nd operand, load/store multiple (but very useful!)

- Thumb1. Really great for beginners. Simplified ARM. Only small downside is about 4x more instruction encoding formats than ARM, and a few specialised instructions don't exist.

- PDP11. Really great for beginners. Problem is lack of modern tool support and old-style stack-based ABI.

- MIPSr2. Pretty great, except for the delay slots and slightly cumbersome conditional branches. Very clean instruction encoding. Much used in university programming courses through the 90s and 00s.

- RISC-V.  Really great. The advantages of MIPS without the problems. University courses and texts are switching to it. The only downside: encoding of literals & offsets inside instructions is not human-decodable.
 

Online brucehoult

  • Super Contributor
  • ***
  • Posts: 3997
  • Country: nz
Re: [C] Pointers - what is the point?
« Reply #72 on: July 19, 2018, 02:22:35 am »
 

Offline GeorgeOfTheJungle

  • Super Contributor
  • ***
  • !
  • Posts: 2699
  • Country: tr
Re: [C] Pointers - what is the point?
« Reply #73 on: July 19, 2018, 02:45:11 am »
I still do 6502 assembly sometimes, just for fun. Not having any 16 bit register is a real PITA (*). The 65c02 was a disappointing upgrade, many mostly unneded additional opcodes that nobody wanted/asked for, and still no 16 bits nowhere.

(*) Strictly speaking it had one: the PC  :)
The further a society drifts from truth, the more it will hate those who speak it.
 

Offline GeorgeOfTheJungle

  • Super Contributor
  • ***
  • !
  • Posts: 2699
  • Country: tr
Re: [C] Pointers - what is the point?
« Reply #74 on: July 19, 2018, 02:51:05 am »
Assembly? No no no, poor Simon, jeez, C is all he needs to learn about pointers!

http://publications.gbdirect.co.uk/c_book/chapter5/pointers.html
« Last Edit: July 19, 2018, 01:51:45 pm by GeorgeOfTheJungle »
The further a society drifts from truth, the more it will hate those who speak it.
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf