Pointerek; tömb, mint pointer

Pointerek

Pl.

    int* p; - egy int-nek a memóriacímét tároló pointer

Példakód:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;

int main()
{
    int szam = 20;

    int *p = &szam; // & - címe (address of) operátor

    cout << szam << endl;
    cout << p << endl;

    cout << *p << endl; // * - dereference operátor
                        //     (címbő megadja a változót)

    *p = 30;
    cout << szam << " " << *p << endl;


    return 0;
}

Tömb, mint pointer

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
using namespace std;

int main()
{
    int t[10] = { 11, 22, 33 };

    cout << t << " " << &(t[0]) << endl;

    int *p = t;

    cout << *p << endl;

    int *q = p + 1;
    cout << *q << endl;

    cout << "------------" << endl;

    cout << t   << " " << *(t+0) << endl;
    cout << t+1 << " " << *(t+1) << endl;
    cout << t+2 << " " << *(t+2) << endl;

    cout << t[0] << " " << t[1] << " "
         << t[2] << endl;
         
     // t[i] igazából csak egy rövidítése a *(t+i)-nek

    return 0;
}

Gyakorlat

Mit ír ki?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
using namespace std;

int hossz(const char *s)
{
    int i = 0;
    while (s[i] != '\0')
        i++;

    return i;
}

int main()
{
    char s[100] = "hello";

    cout << s << endl;

    char *p = s;
    cout << p << endl;

    cout << s+1 << endl; // ello
    cout << s+2 << endl; // llo


    *s = *(s+4);
    cout << s << endl; // oello

    *(s+1) = *(s+4);
    cout << s+1 << endl; // ollo
    cout << *(s+1) << endl; // o

    cout << "-----------" << endl;

    cin >> s;
    cin >> s+1;
    cout << s << endl;

    cout << "-----------" << endl;
    
    cout << hossz("alma") << endl;

    return 0;
}