5

そのため、Cのチュートリアルに従っていますが、構造体はmalloc関数を使用しており、その関数は私のコンパイラ(Visual Studio C ++ 10.0)ではうまく機能しないようです。したがって、私は指示に正確に従い、Cをコンパイルできますが、この特定のコードではエラーが発生します(チュートリアルのWebサイトから文字通り取得したコード)。

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

struct node {
  int x;
  struct node *next;
};

int main()
{
    /* This won't change, or we would lose the list in memory */
    struct node *root;       
    /* This will point to each node as it traverses the list */
    struct node *conductor;  

    root = malloc( sizeof(struct node) );  
    root->next = 0;   
    root->x = 12;
    conductor = root; 
    if ( conductor != 0 ) {
        while ( conductor->next != 0)
        {
            conductor = conductor->next;
        }
    }
    /* Creates a node at the end of the list */
    conductor->next = malloc( sizeof(struct node) );  

    conductor = conductor->next; 

    if ( conductor == 0 )
    {
        printf( "Out of memory" );
        return 0;
    }
    /* initialize the new memory */
    conductor->next = 0;         
    conductor->x = 42;

    return 0;
}

malloc関数は問題を出し続けました:「タイプvoidの値をタイプ "node *"のエンティティに割り当てることができないので、私はすべてのmallocを含む行に(ノード*)をキャストします。

root = malloc( sizeof(struct node) );  

など。これで上記のエラーは解決したようですが、それを実行してコンパイルしようとすると、新しいエラーが発生しました。

1>------ Build started: Project: TutorialTest, Configuration: Debug Win32 ------
1>  TutorialTest.c
1>c:\users\ahmed\documents\visual studio 2010\projects\tutorialtest\tutorialtest\tutorialtest.c(16): error C2065: 'node' : undeclared identifier
1>c:\users\ahmed\documents\visual studio 2010\projects\tutorialtest\tutorialtest\tutorialtest.c(16): error C2059: syntax error : ')'
1>c:\users\ahmed\documents\visual studio 2010\projects\tutorialtest\tutorialtest\tutorialtest.c(27): error C2065: 'node' : undeclared identifier
1>c:\users\ahmed\documents\visual studio 2010\projects\tutorialtest\tutorialtest\tutorialtest.c(27): error C2059: syntax error : ')'
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

そうですね、(完全なC初心者として)これを30分間理解しようとした後、私は解決策を思い付くことができませんでした。このエラーを解決するにはどうすればよいですか?コンパイラの問題だと思い始めていますが、必要がなければコンパイラを変えたくありません。

4

2 に答える 2

15

問題は、CコードをC++コンパイラでコンパイルしていることです。void *Cでは、からオブジェクトポインタへの変換が可能です。C++はそうではありません。

キャストを追加したとのことですが、どのように見えるかは表示されませんでした。このように見える場合、コードはCとC++の両方としてコンパイルする必要があります。

root = (struct node *) malloc(sizeof (struct node));

あるいは、コンパイラーにCとして扱うように指示する方法があるかもしれませんが、そのコンパイラーについては、そこで役立つほど十分にわかりません。

于 2012-06-14T17:08:23.173 に答える
1

5年後、私を含む多くの人々を助けたと思われるこのトピックを見つけました。受け入れられた回答で述べられているように、問題はコードがC ++としてコンパイルされていることが原因であり、C++ではそのような変換は許可されていません。

あるいは、コンパイラーにCとして扱うように指示する方法があるかもしれませんが、そのコンパイラーについては、そこで役立つほど十分にわかりません。

CまたはC++コードをコンパイルするようにコンパイラーに指示できます。コンパイラ.cが選択するには、拡張機能があるだけでは必ずしも十分ではありません。手動で設定するには、Visual Studio 2017で:

ソリューションのプロパティ->C/C++->すべてのオプション->名前を付けてコンパイル->Cコードとしてコンパイル

私のために働いた。それがお役に立てば幸いです。

于 2017-06-01T12:19:06.817 に答える