(int *)a
why use poiunter with intger?

Recommended Answers

All 3 Replies

If a is an integer it doesn't (really) make much sense to do it.

If you are writing something like an operating system, and you have a system structure located at a fixed location, say 0x123456, then it would make sense to cast the integer 0x123456 as a pointer.

Other than that, I can't think of any reason to do it.

Pointers to integers are often used in C programming when you want to set an external variable inside a function, and return some other value. Example:

typedef struct {
  int sizeofbuffer;
  char buffer[1];
} somestruct_t;

int getSizeOfData(somestruct_t* pStruct, int* pBufSize)
{
    int err = 0;
    if (pStruct == 0)
    {
        err = 1;
    }
    else if (pBufSize == 0)
    {
        err = 2;
    }
    else
    {
        *pBufSize = pStruct->sizeofbuffer;
    }
    return err;
}

int myfunc(somestruct_t* pStruct)
{
    int bufsize = 0;
    int err = getSizeOfData(pStruct, &bufsize);
    switch(err)
    {
        case 0: /* Got data */ printf("buffer size == %d\n", bufsize); break;
        case 1: /* Void pointer received */ break;
        case 2: /* Should not happen */ break;
        default: /* Unrecognized error value */ break;
    }
    return bufsize;
}
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.