C中没有malloc的可变字符大小
variable char size without malloc in C
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] = '[=10=]';
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 语言中是否合法...
char res[slen + 1]; /// <<<<<<<<<<<<<<<<<<<<<<<<<<<<< DOES IT WORK AS EXPECTED???
这从 C '99 开始有效。
你对多大有点局限。根据经验,可能不建议超过 8k。请注意,在 Windows 上,如果整个堆栈超过 1mb,程序将崩溃。在现代 Unix 上。同样的事情发生在更大的极限。
不过你不能return。就说
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] = '[=10=]';
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 语言中是否合法...
char res[slen + 1]; /// <<<<<<<<<<<<<<<<<<<<<<<<<<<<< DOES IT WORK AS EXPECTED???
这从 C '99 开始有效。
你对多大有点局限。根据经验,可能不建议超过 8k。请注意,在 Windows 上,如果整个堆栈超过 1mb,程序将崩溃。在现代 Unix 上。同样的事情发生在更大的极限。
不过你不能return。就说