0

我一直在努力理解这段代码的一些片段。它要求输入一些字符串,将计算元音并显示结果。这是一些我不理解的定义,我理解的机制。

在 main() 内部的定义中。我不明白这个'(cad)'在entrada函数中的论点是什么。它上面的一行定义了一个由 3 个指向 char 的指针组成的数组,如果我相信的话,就是 char *cad[N]。我会说我的问题是 Main 函数中的所有内容,参数如何在函数的括号内有意义。之后我明白了。

# include<stdio.h>
# include<stdlib.h>
# include<string.h>
# include<ctype.h>
# define N 3


// Function Prototypes

void salida(char *[], int*);
void entrada(char *[]);
int vocales(char *);

int main ()
{
    char *cad[N];  // declaring an array of 3 pointers to char
    int j, voc[N]; // declaring ints and an array of ints
    entrada (cad);// Function to read in strings of characters. 
    // count how many vowels per line
    for (j = 0; j<N; j++)
    voc[j] = vocales(cad[j]); // it gets the string and sends it to function vocales to count how many vowels. Returns number to array voc[j]
    salida (cad, voc);
}

// Function to read N characters of a string
void entrada(char *cd[] ){
    char B[121]; // it just creates an array long enough to hold a line of text
    int j, tam;

    printf("Enter %d strings of text\n", N );

    for (j= 0; j < N; j++){
        printf ("Cadena[%d]:", j + 1);
        gets(B);
        tam = (strlen(B)+1)* sizeof(char); // it counts the number of characters in one line
        cd[j] = (char *)malloc (tam); // it allocates dynamically for every line and array index enough space to accommodate that line
        strcpy(cd[j], B); // copies the line entered into the array having above previously reserved enough space for that array index
    } // so here it has created 3 inputs for each array index and has filled them with the string. Next will be to get the vowels out of it

}

// Now counting the number of vowels in a line
int vocales(char *c){
    int k, j;

    for(j= k= 0; j<strlen(c); j++)
        switch (tolower (*(c+j)))
        {
            case 'a':
            case 'e':
            case 'i':
            case 'o':
            case 'u':
              k++;
              break;
        }
    return k;
}

// function to print the number of vowels that each line has
void salida(char *cd[], int *v)
{
    int j;

    puts ("\n\t Displaying strings together with the number of characters");
    for (j = 0; j < N; j++)
    {
        printf("Cadena[%d]: %s has %d vowels \n", j+1, cd[j], v[j]);
    }
}
4

1 回答 1

1

cad是一个指针数组。它只有 N 个指针的空间,而不是实际的字符串数据。该entrada函数读取 N 个文本字符串。对于其中的每一个,它都会分配一些空间malloc并在那里复制字符串。 entrada将相应的指针cad(它视为cd)设置为指向分配的缓冲区。

当您将数组作为参数传递时,您不会传递副本。相反,第一个元素的地址被传递给函数。这就是如何entrada修改cad.

于 2012-05-11T18:22:11.393 回答