[英]How can I write c code running on windows?
這段代碼可以在 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;
}
if (num > (*rt)->data)
上的 MSVC 錯誤。
if (num > (*rt)->data)
上的 MingW64 錯誤(分段錯誤)。
通過malloc()
分配的緩沖區中的值最初是不確定的,因此您必須在使用這些值之前對其進行初始化。
這可以這樣做:
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.