[英]making a pointer that stores an element of a char array
我一直在努力找出為什么我得到以下警告:
初始化使指針從整數開始而無需強制轉換
突出顯示的警告是我在下面提到的地方。 我當前正在使用的代碼僅僅是以鏈表形式創建元素樹的開始。 這段代碼似乎工作正常,但是我得到了警告的停靠點。
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','\0'};
// Determines the element
const char *tree = list[0]; // WARNING
ptr = TreeCreate(1, tree);
if (ptr != NULL) {
sprintf(string, "TreeData: %c\n", ptr->data);
OledDrawString(string);
OledUpdate();
}
您的根本錯誤是您將Poitner分配給錯誤的char
const char *tree = list[0]; // WARNING
這不會產生您期望的結果。
在這種情況下, *
不是取消引用Pointe,而是聲明一個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] = {'\0'};
// TEST CODE IN MAIN
char list[6] = {'A', 'B', 'C','\0'};
// Determines the element
const char *tree = &list[0]; // WARNING
ptr = TreeCreate(1, tree);
if (ptr != NULL)
{
sprintf(string, "TreeData: %c\n", ptr->data);
//OledDrawString(string);
//OledUpdate();
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.