0

I'm learning C and have some problems whit pointers. I'm triying to print the memory slot for every declared variable, but when I declare the pointer for a Char[], it just does not work.

Here's my code:

int main () {
    char a[3]; // this variable is my problem
    int b;
    float c;
    char d;
    int e=4;

    char *pachar; //A char type variable for the pointer.
    int *paint;
    float *pafloat;
    char *pacharr;
    int *paintt;

    pachar = &a; // when I try to assign the memory to the pointer, it shows a Warning message.
    paint = &b;
    pafloat = &c;
    pacharr = &d;
    paintt = &e;


    printf("%p \n",pachar);
    printf("%p \n",paint);
    printf("%p \n",pafloat);
    printf("%p \n",pacharr);
    printf("%p \n",paintt);

    return(0);
}

This is the warning message. Am I doing something wrong?

"warning: assignment from incompatible pointer type"

M.M
  • 138,810
  • 21
  • 208
  • 365

3 Answers3

5

You declared a as an array of char:

char a[3];

Name a represents an array, which can be interpreted as a pointer to the initial element of the array. Therefore you do not need & when you assign a to a pointer:

pachar = a;

When you take an address of a in &a expression, you get a pointer to an array of three characters. Trying to assign a pointer-to-an-array to a pointer-to-char triggers compiler warning.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
3

Instead of taking the address of a, you could take the address of the first element. The address of an array is the same as the address of its first element.

pachar = &a[0];
Barmar
  • 741,623
  • 53
  • 500
  • 612
1
char a[3], *pachar;
pachar = a;

printf("Address = %u\n", a); // Base address of the Array. "&a" not required.

printf("Address = %u\n", &a[0]); // Address of the first element.

printf("Address = %u\n", pachar);// Address of the first element.

printf("Address = %u\n", pachar + 0); // Pointer Arithmetic ...

printf("Address = %u\n", pachar + 1); // a[1] is equivalent to pachar + 1

printf("Address = %u\n", &a[1]); // Similar to the above.
Vagish
  • 2,520
  • 19
  • 32
iammowgli
  • 159
  • 4