Hi i got some problems with c pointers...feelin trouble to get through it..here is a problem .anyone plz explain the solutin to me..

#include<stdio.h>
main()
{
int arr[3]={2,3,4};
char *p=arr;
p=(char*)((int*)(p)); printf("%d",*p);
p=(int*)(p+1); printf("%d",*p); }

Recommended Answers

All 7 Replies

char* generally stores the address of char type,here it stores the address of int type.
since char occupy 1 byte memory space while int occupy 2 byte or 4 byte(machine & compiler dependent) space in memory. so on increment in p it will refer to next byte incremented by 1 while the next value is 2 or 4 byte from that address of arr . what I mean to say is that.

Suppose arr has an address of 2000 so p=arr means p has an address of arr.
but arr is of type int so arr[1] will be stored in address 2004.
and on increasing the pointer with value 1 it will point to 2001(as it is of char type) which doesn't contain the value arr[1]. so it will result out 0.

you can refer to arr[1] by :-

p=(int*)(p+2);//if int take 2 bytes
p=(int*)(p+4);//if int take 4 bytes
commented: helpfull reply +0

I got u but when i m increasing the address in
p=(char*)((int*)(p)); printf("%d",*p); by 2 or 4 bytes output is 0..

can u explain this too..

p=(char*)((int*)(p+4));
        printf("%d\n",*p);
p=(char*)((int*)(p)); 
      printf("%d\n",*(p+4));

Both increments are working correctly in my compiler giving output 3.
which compiler are you using..??

Not sure why your handling your pointer that way? Try writing your program like below:

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

#define ELEM_POS 2

int main(int argc, char** argv)
{
    int x[] = {1, 2, 3, 4};
    char *p = (char*)x;

    fprintf(stdout, "p->%d\n", *(int*)p);

    p = (char*)(p + sizeof(int) * ELEM_POS);

    fprintf(stdout, "p->%d\n", *(int*)p);
    return (EXIT_SUCCESS);
}

Yup instead of talking like an unprofessional, i should have used sizeof(int) instead.


@gerard4143:-

p = (char*)(p + sizeof(int) * ELEM_POS);

why are you multiplying sizeof(int) with 2.
it will print element of x[2] instead of x[1].

and
what is the use of command line argument here...I didn't understand. Please Explain.:-O

@cse.avinash
ya i got u..there was some mistake by me..thanx for the help:)

okay.. keep enjoy programming.. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.