简体   繁体   English

如何编写运行在 windows 上的 c 代码?

[英]How can I write c code running on windows?

this code can run on Linux, why not on Windows (MSVC)?这段代码可以在 Linux 上运行,为什么不能在 Windows (MSVC) 上运行?

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef struct node_tag
{
    int data;
    struct node_tag* left;
    struct node_tag* right;
} Tree;

void insert(Tree** rt, int num)
{
    Tree* tmp;
    if (*rt == NULL)
    {
        tmp = (Tree*)malloc(sizeof(Tree));
        if (tmp == NULL)
        {
            fprintf(stderr, "malloc error ");
            exit(1);
        }
        tmp->data = num;
        *rt = tmp;
    }
    else
    {

        if (num > (*rt)->data) {
            insert(&(*rt)->right, num);
        }    
        else {
            insert(&(*rt)->left, num);
        }
         
    }
}

void print_nodes(Tree* root)
{
    if (root == NULL)
    {
        return;
    }

    if (root->left != NULL)
    {
        print_nodes(root->left);
    }

    printf("data= %d\n", root->data);

    if (root->right != NULL)
    {
        print_nodes(root->right);
    }
}

int main(int argc, char** argv)
{
    Tree* root = NULL;
    int arr[] = {
        415,
        456,
        56,
        156,
        51,
        21,
        54,
        3,
        15,
        651,
    };

    int length;
    length = sizeof(arr) / sizeof(arr[0]);
    for (int i = 0; i < length; i++)
    {

        insert(&root, arr[i]);
    }
    print_nodes(root);
    return 0;
}

MSVC errors on if (num > (*rt)->data) . if (num > (*rt)->data)上的 MSVC 错误。

MingW64 errors on if (num > (*rt)->data) (segmentation fault). if (num > (*rt)->data)上的 MingW64 错误(分段错误)。

Values in buffers allocated via malloc() are initially indeterminate, so you must initialize them before using the values.通过malloc()分配的缓冲区中的值最初是不确定的,因此您必须在使用这些值之前对其进行初始化。

This can be done like this:这可以这样做:

Tree* tmp;
if (*rt == NULL)
{
    tmp = (Tree*)malloc(sizeof(Tree));
    if (tmp == NULL)
    {
        fprintf(stderr, "malloc error ");
        exit(1);
    }
    tmp->data = num;
    tmp->left = NULL; /* add this */
    tmp->right = NULL; /* add this */
    *rt = tmp;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM