Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Incompatible pointer type initializing

Tags:

arrays

c

pointers

I'm trying to learn C. I'm currently on pointers so I've decided to write some code to see how it works. However the code works as intended (i.e. it adds chars a-j in an array and prints it on the console) but I'm get warnings about incompatible pointer assignment. I've added the warnings as comments on the lines were the warnings are given.

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


int main(int argc, const char * argv[]) {

    #define MAX 10

    char* c[MAX]; // pointer to the 1st element in the array
    char* pointer = &c; // Warning: Incompatible pointer types initializing 'char *' with an expression of type 'char *(*)[10]'
    for (int j = 0; j < 10; j++)
    {
        *pointer = 'a' + j;
        pointer++;
    }

    pointer = &c; // Warning: Incompatible pointer types assigning to 'char *' from 'char *(*)[10]'
    for (int j = 0; j < 10; ++j)
    {
        printf("i[%d] = %c\n", j, *pointer);
        ++pointer;
    }

    return 0;
}

Can someone please explain why I'm getting these warnings?

char* pointer = &c; & pointer = &c;

I understand the code I'm writing as follows declare a char pointer called pointer and assign the address of the 1st element in the array to the pointer.

PS! please don't comment on how to achieve the same result with better written code as I'm trying to learn here about pointers and arrays. So while this may be a verbose way to achieve this result, I feel it is syntactically correct, so if I've got this wrong please help me understand.

like image 972
Sheedy75 Avatar asked Feb 11 '23 09:02

Sheedy75


2 Answers

Change:

char* pointer = &c

to

char* pointer = c[0];

c elements type is char * but &c type is a pointer to c type.

EDIT: This will fix your warning but the problem is you are dealing with the wrong types first.

Instead of:

char* c[MAX];
char* pointer = &c;

use:

char c[MAX];
char *pointer = c;

In your program you are storing characters, so you need an array of char and not an array of char * elements.

Same for pointer = &c; which then has to be pointer = c;.

like image 93
ouah Avatar answered Feb 13 '23 00:02

ouah


c is an array of pointers to char:

char* c[MAX];

The type of this expression

&c

is "pointer to a length-MAX array of pointers to char", or

char *(*)[MAX]

The compiler is warning you that you're initializing a pointer of one type from one of another type.

It isn't clear what you intended to do with your code, but a valid initialization of a char* with no conversions would be

char* pointer = c[0];

A valid initialization from &c (pointer to an array of pointers), would be

char *(*pointer)[MAX] = &c;

Alternatively, you can let the array "decay" to a pointer to its first element by omitting the address-of operator &", but this yields a pointer to pointer:

char** pointer = c;
like image 41
juanchopanza Avatar answered Feb 12 '23 22:02

juanchopanza