c - 如何更改索引为空的数组值的索引

标签 c arrays validation arrangeoverride

我可以使用 2 个索引的数组来完成此操作,但是当我有 3 个索引的数组时,它只会更改一个值的索引,而当我有 9 个索引时,我的验证就会发出警报。

当我在 3 的数组中输入 11 来接收 011 时,我正在尝试类似的操作,但我得到了 101。

我一直在研究我的第二个函数,我在其中循环索引来切换值。

int validateInt(int digitAmount);
char* validateCharAmount(int charAmount);

int main(void) {
    do{

        printf("Please enter Student's ID': ");
        studentID=validateInt(3);
    }while(studentID!=0);

    return 0;
}

int validateInt(int digitAmount)
{
    int value;
    char *entrySegments;    
    int index=0;
    char temp;
    entrySegments=validateCharAmount(digitAmount);
    while(index<digitAmount){
        while((entrySegments[index]-48)<0 || (entrySegments[index]-48)>9){
            printf("Invalid Value! Please input an integer: ");
            entrySegments=validateCharAmount(digitAmount);
            index=0;
        }
        value=10*value+(entrySegments[index]-48);
        index++;
    }
    printf("%d",value);
    return value;   
}

char* validateCharAmount(int charAmount){

    char entrySegments[charAmount];
    int index=0;
    entrySegments[0]= NULL;
    entrySegments[charAmount]= NULL;
    scanf("%s",entrySegments);
    while(entrySegments[charAmount]!=NULL){
        printf("You entered too many characters! Please input %d: ", charAmount);
        scanf("%s",entrySegments);      
    }
    while(index<charAmount){
        while((entrySegments[index])==NULL){        
            entrySegments[index]=entrySegments[index-1];
            entrySegments[index-1]=48;
        }
        index++;
    }   
    return entrySegments;
}

最佳答案

entrySegmentsvalidateCharAmount 函数内的局部作用域变量。

你不能将它返回给调用者,因为它的生命随着函数结束而结束。

您可以使用malloc & co函数来做到这一点。

此外,entrySegments[charAmount] 寻址数组越界。最后可访问的项目是 entrySegments[charAmount-1]

关于c - 如何更改索引为空的数组值的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41832179/

相关文章:

javascript - 国家代码后面的0怎么去掉

Java 使用没有 namespace 的 XSD 验证 XML

c - 使用 C 的 Libcurl

c# - 将数组拆分为 2 个数组 C#

c++ - 将特定索引处的 char 数组的内容与 char 文字进行比较 - cpp

javascript - 表单仅使用javascript验证一个字段

c - 更新字符串直到在 C 中找到句点

c - Arduino Ethercard - 返回网站内容

有人可以解释这是什么意思吗?

arrays - 数组中元素出现的频率