【问题标题】:variable char size without malloc in C [duplicate]C中没有malloc的可变字符大小[重复]
【发布时间】:2020-12-09 20:54:47
【问题描述】:

char myStr[varLength] 在 C 中工作吗?

我有以下(代码here):

int isVMin(char c){
    return c == 'a' || 
            c == 'e' ||
            c == 'i' ||
            c == 'o' ||
            c == 'u' ||
            c == 'y';
}

int isNum(char c){
    return c>='0' && c<='9';
}

int removeChars(char str[]){ // removes all vowels, returns the digits number
    int slen = strlen(str);
    
    //char* res = malloc(sizeof(char)*slen+1);
    char res[slen + 1]; /// <<<<<<<<<<<<<<<<<<<<<<<<<<<<< DOES IT WORK AS EXPECTED???

    printf("\nthe initial is: '%s'\n", res);
    int numCount = 0, j = 0;
    
    for (int i = 0; i < slen; i++) {
        if (isVMin(str[i]));
            //str[i]= ' ';
        else { 
            res[j++] = str[i];
            if (isNum(str[i]))
            numCount++;
        }
    }
    res[j] = '\0';
    printf("\nthe removed is: '%s'\n", res);
    //str = res;
    return numCount;
}

int main(){
    char phrase[50];
    gets(phrase);
    
    int nb = removeChars(phrase);
    printf("\nLa phrase '%s' contient %d digits", phrase, nb);
    
    return 0;
}

程序按预期编译和工作。但是我怀疑这种用法在 C 中是否合法......

【问题讨论】:

  • 这正是可变长度数组的含义。关键在于名称。
  • OT:您的 isNum 函数复制了标准的 isdigit 函数。
  • 提示:isdigit() 存在。
  • 永远不要使用gets!它非常危险,甚至已从 C 语言规范中删除。使用例如fgets 代替。
  • @Someprogrammerdude:实际上并没有。一个区别是他们的工作与char 的签名无关,而isdigit 的行为在传递EOF 以外的负值时没有定义。

标签: c variable-length-array


【解决方案1】:
char res[slen + 1]; /// <<<<<<<<<<<<<<<<<<<<<<<<<<<<< DOES IT WORK AS EXPECTED???

这从 C '99 开始有效。

你有点受限于多大。经验法则可能不建议超过 8k。请注意,在 Windows 上,如果整个堆栈超过 1mb,则程序将崩溃。在现代 Unix 上。同样的事情发生在更大的范围内。

但是你不能退货。只是说说而已

【讨论】:

  • 这里strdup() 获得一个大致大小的缓冲区可能是一个不错的起点,然后realloc() 修剪它,如果这很重要。
  • 不能退货...?你什么意思?
  • @Serge:意思是不要写char res[slen + 1]; return res;。如果你需要做类似的事情,你毕竟需要malloc()
  • 为什么不返回?这种语言很疯狂
  • @Serge:这种语言并不疯狂。这种语言不会在你背后做事,因此不能在堆上隐式分配数组。在进行内核模式工作时,明显缺乏保护措施本身就成为一种真正必要的保护措施。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-23
  • 2010-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多