Search code examples
ccastingdouble-pointer

Typecasting a double pointer in C


I can't figure out this error during parameter passing.

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

typedef char my_char;

void myfunc(const my_char** data)
{
    printf ("%s\n", *data);
    printf ("%s\n", *(data + 1));
}

int main(){

    char **mydata;
    mydata = malloc(sizeof(char*)*2);
    mydata[0] = malloc(sizeof(char)*50);
    mydata[1] = malloc(sizeof(char)*50);

    memset(mydata[0],'\0',50);
    memset(mydata[1],'\0',50);
    strcpy (mydata[0], "Hello");
    strcpy (mydata[1], "world");

    myfunc((my_char**)mydata);

    free (mydata[0]);
    free (mydata[1]);
    free (mydata);

    return 0;
}

It works properly. But gives a warning when I typecast the argument explicitly. Why is this so? The warning displayed is :

warning: passing argument 1 of ‘myfunc’ from incompatible pointer type

As far as I know, the typecasting should help the compiler understand , what type of data the pointer is holding on to. But here its not helping at all.


Solution

  • Use const while typecasting the datatype.

    myfunc((const my_char**)mydata);
    

    You are getting that value as a const in a function.