我编写了一段代码,它在 CodeBlocks 13.12 中完美编译,没有错误! 我将相同的代码复制到 VS2010 它显示 1 个错误:
IntelliSense: identifier "malloc" is undefined
代码块代码:
#include <stdio.h>
#define maxLength 4
typedef short int *set;
void func(set *a)
{
*a=malloc(maxLength*sizeof(set));
(*a)[0]=10;
(*a)[1]=13;
(*a)[2]=15;
}
void main()
{
set a;
func(&a);
printf("%d %d %d",a[0],a[1],a[2]);
}
VS2010代码:
#include "stdafx.h"
#include <stdio.h>
#define maxLength 4
typedef short int *set;
void func(set *a){
*a=malloc(maxLength*sizeof(set));
(*a)[0]=10;
(*a)[1]=13;
(*a)[2]=15;
}
int _tmain(int argc, _TCHAR* argv[])
{
set a;
func(&a);
printf("%d %d %d",a[0],a[1],a[2]);
return 0;
}
不知道是什么问题..
如果我添加预编译代码:#include <iostream>
错误继续,但出现另一个错误:
IntelliSense: a value of type "void *" cannot be assigned to an entity of type "set"
新代码
void func(set *a){
func(a);
}
void func1(set *a){
*a=reinterpret_cast<set>(malloc(maxLength*sizeof(set)));
(*a)[0]=10;
(*a)[1]=13;
(*a)[2]=15;
}
如何在函数调用的函数中创建数组?
最佳答案
您似乎有两个问题。第一个也是最严重的是您缺少头文件。参见例如this malloc
reference 。不包含此头文件将导致您的内存分配现在按您的预期工作。
另一个错误是您实际上似乎使用的是 C++ 而不是 C。 In C you should not cast the return of malloc
,但在 C++ 中你必须这样做。
关于c - 相同的两个代码,但其中之一在 c [代码块]-[VS2010] 中仍然有错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21509354/