making a pointer that stores an element of a char array

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error making a pointer that stores an element of a char array on this date .

I’ve been struggling trying to figure out why I am getting the following warning:
initialization makes pointer from integer without a cast

The highlighted warnings are where I mentioned below. The code I am currently using is just the beginning of creating tree of elements in a linked list fashion. This code seems to be working fine however I get docked points for warnings.

typedef struct Node {
        struct Node *leftChild;
        struct Node *rightChild;
        char data;
} Node;

Node *TreeCreate(int level, const char *data) {
    struct Node *ptr = (struct Node*) malloc(sizeof (Node));
    if (ptr == NULL) {
        // malloc failed
        return 0;
    }
    ptr->data = data;   // WARNING
    ptr->leftChild = NULL;
    ptr->rightChild = NULL;
    return ptr;
}
// TEST CODE IN MAIN
char list[6] = {'A', 'B', 'C',''};

// Determines the element
const char *tree = list[0]; // WARNING
ptr = TreeCreate(1, tree);
if (ptr != NULL) {
    sprintf(string, "TreeData: %cn", ptr->data);
    OledDrawString(string);
    OledUpdate();
}

Answer

Your fundamental mistake is that you are assigning a poitner to a char which is wrong

const char *tree = list[0]; // WARNING

this will not yield the result you expect.

The * in this case is not dereferencing the pointe, you are declaring a poitner and pointeing to a char with it, then when you try to access the pointer, your program tries to read at an invalid memory address causing undefined behavior.

Then you do the opposite thing in

ptr->data = data;

you should enable compiler warnings to avoid this mistakes.

To handle the data you apparently want to handle, first you need to redefine the struct like this

typedef struct Node {
    struct Node *leftChild;
    struct Node *rightChild;
    char *data;
    /*   ^ this should be a char pointer */
} Node;

then in the TreeCreate() function, copy the data by first allocating space and then using memcpy() like this

Node *TreeCreate(int level, const char *data) {
    size_t       length;
    struct Node *ptr;

    ptr = malloc(sizeof (Node));
    if (ptr == NULL) {
        return NULL;
    }
    if (data != NULL)
    {
        length    = strlen(data);
        ptr->data = malloc(1 + length);
        if (ptr->data != NULL)
            memcpy(ptr->data, data, 1 + length);
    }
    else
        ptr->data = NULL;        

    ptr->leftChild  = NULL;
    ptr->rightChild = NULL;

    return ptr;
}