0

このコードの一部を理解するのに苦労しています。いくつかの文字列を入力するように求められ、母音を数えて結果を表示します。私が理解していないのはいくつかの定義、私が理解できる仕組みです。

main() 内の定義。この '(cad)' が entrada 関数に含まれている引数の意味がわかりません。その上の 1 行には、char への 3 つのポインターの配列、つまり 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の対応するポインタを設定します。cadcd

配列を引数として渡す場合、コピーは渡されません。代わりに、最初の要素のアドレスが関数に渡されます。これはentrada、 のポインターを変更する方法cadです。

于 2012-05-11T18:22:11.393 に答える