C 错误:表达式必须有一个常量值(windows 代码示例) [英] C error: expression must have a constant value (windows code example)

查看:62
本文介绍了C 错误:表达式必须有一个常量值(windows 代码示例)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试编译代码编辑控件"

I have been trying to compile the code "Edit control"

从这里:http://zetcode.com/gui/winapi/controls/

现在我的编译器 (VS2013) 不会让我编译这段代码,同时给我这个错误:错误 574 错误 C2057:预期的常量表达式

now my compiler (VS2013) wont let me compile this code while giving me that error: Error 574 error C2057: expected constant expression

代码部分:

    if (HIWORD(wParam) == BN_CLICKED) {

            int len = GetWindowTextLengthW(hwndEdit) + 1;
            wchar_t text[len];

            GetWindowTextW(hwndEdit, text, len);
            SetWindowTextW(hwnd, text);
        }

我用这个代码来解决这个问题:

i have used this code to fix the problem:

wchar_t *text = calloc(len, sizeof(wchar_t));
if (text != NULL)
{
    // STUFF
}
free(text);

推荐答案

虽然 C99 支持 VLA Microsoft 不支持它们.

While C99 support VLA Microsoft doesn't support them.

这意味着

wchar_t text[len];

对 Visual Studio 2013 c 编译器无效.

is not valid with Visual Studio 2013 c compiler.

您可以使用 malloc 来这样做:

You can use malloc to do so:

wchar_t *text = malloc(sizeof(wchar_t)*len);
if (text != NULL)
{
    // STUFF
}
free(text);

编辑

请注意,malloc指定的内存未初始化,与堆栈分配的 VLA 一样,因此必须在需要时使用以下方法初始化内存:

Take note that mallocated memory is not initialized, as with VLAs that are stack allocated, so memory must be inited if needed using:

memset(text, 0, sizeof(whar_t)*len);

或使用 calloc 而不是 malloc:

or using calloc instead of malloc:

wchar_t *text = calloc(len, sizeof(wchar_t));
if (text != NULL)
{
    // STUFF
}
free(text);

这篇关于C 错误:表达式必须有一个常量值(windows 代码示例)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆