c - 相同的两个代码,但其中之一在 c [代码块]-[VS2010] 中仍然有错误

标签 c visual-studio-2010 codeblocks

我编写了一段代码,它在 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/

相关文章:

c++ - 如何在 C++ win32 API 的对话框中设置图像?

多个测试文件的CMake配置

visual-studio-2010 - VisualStudio 2010 无法加载类图 "Exception of type ' System.Exception' 被抛出。”

c - 单击代码块中的“构建并运行”后,错误 : CentralTendencies. exe 已停止工作

c++ - Code::Blocks 和 boost 1.55:存在动态库时不使用静态库

c - 变量多重定义警告

c - 是否可以使用 openssl 的 EVP api 用公钥解密

c - 这个涉及后增量运算符的表达式是如何求值的?

c# - 在 WPF 应用程序中添加和执行小型 .net "scripts"

visual-studio - Microsoft Visual Studio 2010 学术版