本文介绍了const变量无法识别为数组维的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

long AnsiString::pos(const char* plainString) const {
const size_t patternLength = strlen(plainString);
if (patternLength == 0) return -1;

size_t stringLength = count;
int partialMatch[patternLength]; // int* partialMatch = new int[patternLength];

KMPBuildPartialMatchTable(plainString, partialMatch);

int currentStringCharacter = 0;
int currentPatternCharacter = 0;
while (currentStringCharacter < stringLength) {
    if (currentPatternCharacter == -1) {
        currentStringCharacter++;
        currentPatternCharacter = 0;
    }
    else if (items[currentStringCharacter] == plainString[currentPatternCharacter]) {
        currentStringCharacter++;
        currentPatternCharacter++;
        if (currentPatternCharacter == patternLength) return currentStringCharacter - currentPatternCharacter;
    } else {
        currentPatternCharacter = partialMatch[currentPatternCharacter];
    }
}

// delete(partialMatch);

return -1;
 }

在使用Visual C ++实现此claas方法时,出现了错误.

I get an error in the implementaation of this claas method using visual c++.

int partialMatch[ patternLength ] ; // expression must have a constant value

(我正在使用其他语言的VS,因此您会发现一些差异).

(I'm using VS in other language so you could find some differences).

正如您所见,我将patternLength声明为一个常量.解决方案在ccode中有注释,但我不想使用动态内存分配.有什么主意吗?

I declared patternLength as a constant as you can see. A solution is commented in the ccode but i don't want to use dynamic memory allocation. Some idea ?

推荐答案

在编译时必须知道数组大小.

Array sizes must be known at compile time.

const变量不能确保做到这一点. const限定符确保变量一旦初始化就无法修改.

A const variable does not ensure that. The const qualifier ensures that the variable cannot be modified once it is initialized.

在编译时可能会知道const变量的值.如果编译器可以检测到该变量,则可以使用该变量来定义数组的大小.

It is possible for the value of const variable to be known at compile time. If a compiler can detect that, then the variable can be used to define the size of an array.

更经常地,在编译时不知道const变量的值.它在运行时用一个值初始化,该值在变量初始化后不能更改.这不适合用于定义数组的大小.

More often, the value of a const variable is not known at compile time. It is initialized with a value at run time, which can't be changed after the variable is initialized. That does not make it fit for use to define the size of an array.

如果希望能够在编译时使用变量,请改用constexpr.编译器将尽最大努力在编译时评估该值.如果无法在编译时评估变量的值,则会失败.

If you want to be able to use the variable at compile time, use constexpr instead. The compiler will do its best to evaluate the value at compile time. It will fail if the value of the variable cannot be evaluated at compile time.

这篇关于const变量无法识别为数组维的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 22:16