Pointer + For Loop Where the Drama ?

Mar 19, 2012 at 5:52am
My for loop doesn't print value of array via pointer . What am I missing ?

side note is this valid?

1
2
3
4
5
6
7
int count = 0; 

for ( count ; count < 4 ; count++ ) 
{
     Statement; 
}



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
45
46
47
48
49


#include <stdio.h>
#include <stdlib.h>

int main()
{

    int x, y ;
    x =5;
    y =10;
    int z[ ] ={1,2,4,8,16};

    printf(" The address of x is : %p\n\n " , &x);
    printf(" The address of y is : %p\n\n " , &y);
    printf(" The address of z[0] is : %p\n\n " , &z[0]);

    int *testPtr = &x;

    printf(" The value of x is : %i\n\n " , *testPtr);

     *testPtr = *testPtr + 6; // wouldnt work otherwise

    printf(" The address of x is : %i\n\n " , *testPtr);

    if ( *testPtr > y)
    {
        printf(" x > y \n\n" );
    }
    else
    {
        printf(" x < y \n\n");
    }

    testPtr = &z[0];

   [b] int count;

    for ( count = 0 ; count < 4 ; count++)
    {
        printf( " The value of testPtr at %i \n\n", *testPtr +count);
    }[/b]


    return 0;
}


Mar 19, 2012 at 6:23am
nathansetokaiba wrote:
What am I missing ?

Parenthesis
1
2
3
4
for ( count = 0 ; count < 5 ; count++)//use <5 or <=4 if you want all values in array
{
     printf( " The value of testPtr at %i \n\n", *(testPtr +count));
}
Last edited on Mar 19, 2012 at 6:23am
Mar 19, 2012 at 6:30am
I think this is what you want.
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
45
46
47
48
49

#include <stdio.h>
#include <stdlib.h>

int main()
{

    int x, y ;
    x =5;
    y =10;
    int z[ ] ={1,2,4,8,16};

    printf(" The address of x is : %p\n\n " , &x);
    printf(" The address of y is : %p\n\n " , &y);
    printf(" The address of z[0] is : %p\n\n " , &z[0]);

    int *testPtr = &x;

    printf(" The value of x is : %i\n\n " , *testPtr);

    
    printf(" The address of x is : %p\n\n " , testPtr);

    if ( (*testPtr) > (y))
    {
		
        printf(" x > y \n\n" );
    }
    else
    {
        printf(" x < y \n\n");
    }

    testPtr = z;

  int count;

    for ( count = 0 ; count <= 4 ; count++)
    {
        printf( " The value of testPtr at %i \n\n", testPtr[count]);
       // or   printf( " The value of testPtr at %i \n\n", *(testPtr +count));
    }


    return 0;
}


Last edited on Mar 19, 2012 at 6:37am
Topic archived. No new replies allowed.