I'm currently doing MIT Opencourseware's Practical Programming in C. I'm finding pointers a little bit confusing. Here are some questions:

1)
int *pa=arr
Suppose char * pc = (char*)pa; what value of i satisfies
(int *)(pc+i)== pa + 3? [Answer:i=12]

I get that the address is 12 bits down because each int is 4 bits. But other than that I don't understand much. What's difference does it make inclosing char* in parenthesis?. If someone could example what each equation means I'd greatly appreciate it.
2) What's the difference between *pointername and pointername?

Thanks!

1. The parantheses means type casting -- converting one type of pointer into another. You will see that syntax quite often in C programs. One way to easily find out how things work or don't work is to try it in a very small program. If you omit the parentheses the compile will not know what to do with the "char" part of the typecast.

2. *pointername is dereferencing the pointer, or looking at the value in the address contained in the pointer. Without the asterisk its only using the name of the pointer.

int *pointername; // declares a pointer
int x;
pointername = &x; // set pointername to reference a variable
*pointername = 0; // assign the value of 0 to integer x.

AD, thanks for the help. I'm still having trouble understanding the first part though. Could you explain how (int *)(pc+i)== pa + 3 yields i = 12?

AD, thanks for the help. I'm still having trouble understanding the first part though. Could you explain how (int *)(pc+i)== pa + 3 yields i = 12?

I quickly looked at your posting and have one question

int *pa=arr

What's arr?

On most 32-bit compilers, the size of an integer is 4 bytes. Since pa is an int pointer incrementing the pointer by 1 will advance the memory location 4 bytes.

A character pointer only occupies one byte of memory, so advancing a pointer by 1 wil increment the memory location by only one byte.

So in the original post pa+3 advances pa by 3*4 = 12 bytes. To do the same with pc you have to add 12 to pc to get pc to point to the same memory location that pa will point to.

The rule is: the compiler increments the pointer by the number of bytes to which it points. char *ptr, ptr = ptr + 1 the value of pointer is advances by 1 because sizeof(char) is always 1. int *ptr, ptr = ptr + 1 this pointer is advanced by sizeof(int) * 1 bytes, or on 32-bit compilers sizeof(int) = 4. If your compiler supports long long then such a pointer will be advanced (most likely) by 8 bytes because sizeof(long long) = 8.

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.