简体   繁体   中英

Pointer and array memory

I am confused between the output of the following code:

char *s[]={"knowledge","is","power"};
char t[]={"Hello"};
char **p,*q;
p=s;
q=t;
cout<<++*p;
cout<<*p++;
cout<<++*p;
cout<<++*q;

Now, the Output is nowledge nowlegde s I .

Please explain how the memory allocation is taking place in both arrays.

char *s[] = {"knowledge", "is", "power"};

       ===========================================================
addr1: | 'k' | 'n' | 'o' | 'w' | 'l' | 'e' | 'd' | 'g' | 'e' | 0 |
       ===========================================================

       =================
addr2: | 'i' | 's' | 0 |
       =================

       ===================================
addr3: | 'p' | 'o' | 'w' | 'e' | 'r' | 0 |
       ===================================

       =========================
addr4: | addr1 | addr2 | addr3 |
       =========================

    s: addr4

.

char *t[] = {"Hello"};

       ===================================
addr5: | 'H' | 'e' | 'l' | 'l' | 'o' | 0 |
       ===================================

       =========
addr6: | addr5 |
       =========

    t: addr6

.

char **p,**q;
p=s;
q=t;

    p: addr4
    q: addr6

.

++*p;

     p: addr4
    *p: addr1
  ++*p: addr1 + 1
(!) *p: addr1 + 1

.

*p++;

     p: addr4
    *p: addr1 + 1
  *p++: addr1 + 1
(!)  p: addr4 + 1

.

++*p;

     p: addr4 + 1
    *p: addr2
  ++*p: addr2 + 1
(!) *p: addr2 + 1

.

++*q;

     q: addr6
    *q: addr5
  ++*q: addr5 + 1
(!) *q: addr5 + 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM