What does this quote about char pointers mean?

后端 未结 4 1692
长情又很酷
长情又很酷 2021-01-24 06:24

I\'ve read a paragraph but I can\'t understand what does it mean....can anyone please explain? the paragraph is :

processing a single character as a cha

相关标签:
4条回答
  • 2021-01-24 07:02

    It means, if you have a single character, i.e.:

    char c = 'p';
    

    Do not try to dereference c, i.e., to do *c, because it will lead to undefined behaviour.

    0 讨论(0)
  • 2021-01-24 07:09

    It means you shouldn't do something like:

    char *pCh = 'A';  // this is the value 0x41 (assuming ASCII).
    char Ch = *pCh;   // probably not what you wanted.
    

    because there is a vast difference between a character and a character pointer.

    In fact, a decent compiler should give you a warning when you attempt to do something like that.

    The rest of it explains one possible effect. If you're working in a system where char values are eight bits, they will only be able to hold values from 0 through 255 inclusive (the ISO C standard allows char values to be larger but it's fairly uncommon). It's very unlikely that a pointer chosen at random from that value set will be useful.

    It's not totally out of the question since you may be on an embedded system where you have memory-mapped I/O down there but, in that case, you'd be more likely to use something like #define IOPORT7 0x0041 and use IOPORT7 rather than 'A'.

    Pointers, on the other hand, tend to be able to point at your entire address space, which can be 32 bits wide (or larger). 32 bits gives you about four billion possible values where a pointer can point to.

    0 讨论(0)
  • 2021-01-24 07:18

    I'd dump the book or whereever you got that quote from. What is probably meant is you shouldn't try something like this:

    char c = 'a';
    strcmp(&c,"a"); // might accidentally work on some systems, but behaviour is undefined
    
    0 讨论(0)
  • 2021-01-24 07:19

    I'm a little worried about the source of that paragraph -- it feels pretty ancient.

    Every modern operating system provides protected memory. Every process gets its own address space, and the physical machine's low memory is not accessible to programs without performing some pretty significant operations (such as iopl(2) or ioperm(2) on Linux systems).

    The low memory is not mapped into processes because it is the easiest way to catch attempts to write to the NULL pointer (which is essentially the address 0x0) and char variables (rather than char * variables). The OS could perfectly well map the page at virtual address 0x0 to any page of memory it wants. (Mapping the zero-page is sometimes required for compatibility mode execution of ancient or arcane systems.)

    Of course, if you're reading a guide on programming machines without MMUs, then it makes some sense, but I'd still be wary.

    0 讨论(0)
提交回复
热议问题