C 为什么我的;";变量在达到for循环中的第三个周期时呈指数增长?
我遇到了一个问题,这里的一个程序是一个数据输入例程,问题是变量c,当它达到字符串的第三个周期时,它会去capac函数询问用户字符串的最大容量,因为它开始增长,上帝知道如何使我的for变得不可用C 为什么我的;";变量在达到for循环中的第三个周期时呈指数增长?,c,string,function,for-loop,C,String,Function,For Loop,我遇到了一个问题,这里的一个程序是一个数据输入例程,问题是变量c,当它达到字符串的第三个周期时,它会去capac函数询问用户字符串的最大容量,因为它开始增长,上帝知道如何使我的for变得不可用 #include<stdio.h> #include<stdlib.h> #include<conio.h> #include<string.h> int func_carac(int *car) //function that catches char
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<string.h>
int func_carac(int *car) //function that catches characters introduced by the user
{
int caracter;
printf("\nType the character you want: \n");
caracter = getche();
*car = caracter;
return *car;
}
//________________________________________________________\\
int func_capac(int *cap) //function to ask the user for the amount of characters
{
int quant;
printf("\nDetermine the maximum character capacity you want to write: ");
scanf("%d",&quant);
*cap = quant;
return *cap;
}
int main()
{
int car, pos, c, total;
char vetor[] = {'\0'};
func_capac(&c);
total = c + 1;
vetor[total];
vetor[total] = '\0';
printf("%i", c);
for(pos = 0; pos < c; pos++)
{
func_carac(&car);
if((car >= 97) && (car <= 122) || (car == 32))
{
printf("\n%c - Tabela ASCII, %d \n",car ,car);
printf("%i", c);
vetor[pos] = (char) car;
}
else if(car == 8)
{
printf("Successfully removed the previous character.");
pos = pos-2;
}
else
{
pos--;
}
}
printf("Frase: %s\n",vetor);
}
#包括
#包括
#包括
#包括
int func_carac(int*car)//捕捉用户引入的字符的函数
{
内特字符;
printf(“\n键入所需字符:\n”);
caracter=getche();
*car=caracter;
返回*汽车;
}
//________________________________________________________\\
int func_capac(int*cap)//用于向用户询问字符数的函数
{
整数;
printf(“\n确定要写入的最大字符容量:”;
scanf(“%d”、&quant);
*上限=数量;
返回*上限;
}
int main()
{
内部车辆,位置,c,总计;
char vetor[]={'\0'};
func_capac(&c);
总数=c+1;
审查员[总数];
审核人[总数]='\0';
printf(“%i”,c);
用于(pos=0;pos 如果((car>=97)和((car@Someprogrammerdude)搞定了它。vector[]={'\0'}
意味着向量是长度为1的数组。当您在位置0后写入向量时,您最终会出现未定义的行为(即以某种方式覆盖c)。以下是最小修复:
int main()
{
int car, pos, c, total;
func_capac(&c);
total = c + 1;
char vetor[total];
for(int i = 0; i < total; i++) vetor[i] = 0; // or memset(vector, 0, total);
...
intmain()
{
内部车辆,位置,c,总计;
func_capac(&c);
总数=c+1;
char vetor[总计];
for(int i=0;i
在函数中,为什么要同时使用引用传递模拟和返回值?选择其中一个,而不是两个(我建议只返回值)。另外,我认为,您标记这个窗口,conio.h/getche不是posix。至于您的问题,C没有动态数组。数组向量被定义为只包含一个元素。任何非零索引都将超出范围,并导致未定义的行为。vetor[total];
什么也不做。@AllanWind除了超出数组的边界之外。