简体   繁体   English

为什么我的 strcmp 突然结束我的程序?

[英]why is my strcmp ending my program abruptly?

#include <stdio.h>
#include <string.h>

void processString(char *str, int *totVowels, int *totDigits);

int main()
{
    char str[50], *p;
    int totVowels, totDigits;

    printf("Enter the string: \n");
    fgets(str, 80, stdin);

    if (p = strchr(str, '\n')) *p = '\0';

    processString(str, &totVowels, &totDigits);
    printf("Total vowels = %d\n", totVowels);
    printf("Total digits = %d\n", totDigits);

    return 0;
}

void processString(char *str, int *totVowels, int *totDigits)
{
    int i, j;
    char tester[11] = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};

    *totDigits = 0;
    *totVowels = 0;

    for (i = 0; i < strlen(str); i++)
    {
        if (isdigit(str[i]))
        {
            *totDigits += 1;
        }
        else if(isalpha(str[i]))
        {
            for (j = 0; j < 11; j++)
            {
                if (strcmp(str[i], tester[j]) == 0)
                {
                    *totVowels+=1;
                }
            }
        }
    }
}

My code is trying to calculate the number of times a number and vowel appeared in a string.我的代码试图计算数字和元音出现在字符串中的次数。

My string compare is trying to check for vowels but the program ends when it reaches the strcmp line.我的字符串比较试图检查元音,但程序在到达strcmp行时结束。 Why is that happening?为什么会这样? Is my syntax wrong?我的语法错了吗?

PS I'm only allowed to edit in the processString function, the rest are all given. PS我只允许在processString函数中编辑,其余的都给了。

Your problems lies is the code if (strcmp(str[i], tester[j]) == 0) .您的问题在于代码if (strcmp(str[i], tester[j]) == 0) Because you are referencing single-dimensional arrays, the dereference comes out to be a single character.因为您正在引用一维数组,所以取消引用结果是单个字符。 Essentially you are comparing two chars , and chars can be compared for equality like ints .本质上,您是在比较两个chars ,并且可以比较chars是否相等,例如ints And strcmp is designed for comparing strings , not single chars .并且strcmp设计用于比较字符串,而不是单个chars That is why it segfaults (segfaults are due to invalid pointer dereferences. In this case it tried to dereference a non-pointer. A definite no-no.)这就是它出现段错误的原因(段错误是由于无效的指针取消引用造成的。在这种情况下,它试图取消引用一个非指针。一个明确的禁忌。)

The fix would be to replace that line with: if (str[i] == tester[j]) .解决方法是将该行替换为: if (str[i] == tester[j])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM