c-制作一个指针,用于存储char数组的一个元素



我一直在努力弄清楚为什么会收到以下警告:
初始化使指针从整数变为不带强制转换

我在下面提到了突出显示的警告。我目前使用的代码只是以链表方式创建元素树的开始。这个代码似乎工作得很好,但是我得到了警告的停靠点。

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();
}

您的根本错误是将poitner分配给错误的char

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

这不会产生你所期望的结果。

在这种情况下,*不是取消引用指针,而是声明一个poitner并用它指向char,然后当你试图访问指针时,你的程序试图读取无效的内存地址,导致未定义的行为。

然后你在中做相反的事情

ptr->data = data;

应该启用编译器警告以避免出现这种错误。

要处理您显然想要处理的数据,首先需要重新定义像这样的结构

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

然后在TreeCreate()函数中,通过首先分配空间,然后像这个一样使用memcpy()来复制数据

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;
}

我想我明白了。以下修复了我的警告。感谢您的快速响应!

const char *tree = &list[0];
ptr->data = *data;
the following, a complete program, 
that cleanly compiles
and has the warnings fixed
and eliminates the clutter and unnecessary typedef statements.
#include<stdio.h>
#include<stdlib.h>

struct Node 
{
        struct Node *leftChild;
        struct Node *rightChild;
        char data;
};
struct Node *TreeCreate(int level, const char *data) 
{
    struct Node *ptr = malloc(sizeof (struct Node));
    if (ptr == NULL) 
    {
        // malloc failed
        return NULL ;
    }
    // implied else, malloc successful
    ptr->data = *data;   // WARNING
    ptr->leftChild = NULL;
    ptr->rightChild = NULL;
    return ptr;
}
int main()
{
    struct Node *ptr = NULL;
    char  string[120] = {''};
    // 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();
    }
    return 0;
}

相关内容

最新更新