請考慮VC++ 2010中的以下C代碼,用於在C語言中創建BST。通過在VC++項目中創建win32控制檯應用程序。C++ malloc代碼中的VC++ 2010錯誤
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
typedef struct BSTNode
{
char *data;
struct BSTNode *left,*right;
}Node;
Node *createNode(char *str)
{
int strLength=strlen(str);
char *data=(char *)malloc(strLength+1);
strcpy(data,str);
data[strLength+1]='\0';
Node *temp=(Node *)malloc(sizeof(Node));
temp->left=0;
temp->right=0;
temp->data=data;
return temp;
}
int main()
{
Node *root=createNode("Ravinder");
printf("%s\n",root->data);
return 0;
}
它給出錯誤的VC++ 2010:
warning C4996: 'strcpy': This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. c:\users\radha krishna\documents\visual studio 2010\projects\binarysearchtree\binarysearchtree\main.c 17
warning C4047: 'return' : 'Node *' differs in levels of indirection from 'int' c:\users\radha krishna\documents\visual studio 2010\projects\binarysearchtree\binarysearchtree\main.c 25
error C2275: 'Node' : illegal use of this type as an expression c:\users\radha krishna\documents\visual studio 2010\projects\binarysearchtree\binarysearchtree\main.c 20
error C2223: left of '->right' must point to struct/union c:\users\radha krishna\documents\visual studio 2010\projects\binarysearchtree\binarysearchtree\main.c 22
error C2223: left of '->left' must point to struct/union c:\users\radha krishna\documents\visual studio 2010\projects\binarysearchtree\binarysearchtree\main.c 21
error C2223: left of '->data' must point to struct/union c:\users\radha krishna\documents\visual studio 2010\projects\binarysearchtree\binarysearchtree\main.c 23
error C2065: 'temp' : undeclared identifier c:\users\radha krishna\documents\visual studio 2010\projects\binarysearchtree\binarysearchtree\main.c 20
error C2065: 'temp' : undeclared identifier c:\users\radha krishna\documents\visual studio 2010\projects\binarysearchtree\binarysearchtree\main.c 21
error C2065: 'temp' : undeclared identifier c:\users\radha krishna\documents\visual studio 2010\projects\binarysearchtree\binarysearchtree\main.c 22
但是,如果我取代上述功能createnode通過這一點,做工精細:
Node *createNode(char *str)
{
Node *temp=(Node *)malloc(sizeof(Node));
temp->left=0;
temp->right=0;
temp->data=str;
return temp;
}
在第一個塊中收集變量的聲明。並刪除'data [strLength + 1] ='\ 0';'。 – BLUEPIXY 2014-11-25 10:50:34
這是C.在函數的開頭聲明'Node * temp'。 – 2014-11-25 10:52:22
@barakmanos:應該是:「這是C89」 - 現代C編譯器至少支持C99 - 只有MSVC仍然存在於黑暗時代。 – 2014-11-25 10:53:37