簡體   English   中英

C-這樣使用malloc有什么問題?

[英]C - What's wrong with using malloc like this?

typedef struct node node;

//  LinkedList data structure to hold characters.
struct node {
    char character;
    node *link;
};

稍后我嘗試:

node *tmp = malloc(sizeof (node));

我在文本編輯器中收到一條錯誤消息:

clang: warning: treating 'c' input as 'c++' when in C++ mode, this behavior is deprecated
error: cannot initialize a variable of type 'node *' with an rvalue of type 'void *'
            node *tmp = malloc(sizeof (node));
                  ^     ~~~~~~~~~~~~~~~~~~~~~
    1 error generated.
    [Finished in 0.1s with exit code 1]

我在Xcode中遇到了同樣的錯誤,但是在Terminal中使用gcc可以正常工作並且編譯良好。 怎么會?

提前致謝。

malloc返回類型void *。 您想要的是將void *的原始緩沖區區域轉換為節點*。

通過在malloc之前添加(node*) malloc ,您正在使用C樣式強制轉換。 在GCC中,編譯器會將未廣播的內存自動匹配到node* 但是,對於C ++編譯器而言,這不是標准行為。 同時,如果您通過添加-Wall選項打開警告,則應該看到錯過的演員的警告。

在此方面,CLang比GCC嚴格得多。 它基本上不允許任何不符合標准和Apple衍生標准的東西。

要正確解決此問題,您需要

  1. 在malloc之前添加(node *)強制轉換
  2. extern "C" { ... }子句包裝整個代碼體。
  3. 如果需要,使用#ifdef確定編譯器是否為c ++編譯器。

這將確保編譯器理解該代碼是c代碼,並且類型轉換將正確執行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM