Hi everybody, can someone please explain what is the difference between line A(10) and line B(11).why am i being able to access value of n without using de-referencing operator in first case?

void fun(void *n)
{
    printf("\n n=%d ", n);
}

int main()
{

    char nVal = 65;
    fun((int*)nVal);        //-----A
    fun((int*)&nVal);       //-----B
    return 0;
}

output is 
n=65
n=2359119

thanks in advance

Because what you're passing on line A is not a pointer to nVal, it is a pointer with value 65, and you are printing the value of the pointer.
On line B you pass the address of nVal, so a pointer with value 2359119.

So in the first case you are not accessing the value of nVal, you're reading a copy of nVal, just casted to a pointer.

The printf function is not type-safe (it is from C, which is only weakly typed). The printf interprets its parameter types (after the formatted string) based on the format values in the string. So, if you have %d in the string, it will interpret whatever the second parameter is as an int, regardless of what type it actually has. So, if you pass a pointer (void or other-wise), it will print-out whatever address is stored in the pointer.

When you call fun(), at lines 10 and 11, you are also doing a type-unsafe conversion (C-style cast). Using this (int*) cast is going take anything (and I mean _anything_) and blindly assume its value is the address of an int variable. So, in the first version it assumes the value of the char is an address of an int (in fact, it will assume that the 1 byte of the char is 1 byte out of 4 or 8 bytes that represent the pointer, it just happens that the other 3 or 7 bytes in memory are zero, but that's just luck). So, in the first case, you get the value of the char printed out, while in the second case, you get the address of the char printed out.

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.