gpt4 book ai didi

C语言 : args in functions inside Main (). 不清楚它们是什么

转载 作者:行者123 更新时间:2023-11-30 15:57:21 32 4
gpt4 key购买 nike

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

在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]);
}
}

最佳答案

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

当您传递数组作为参数时,您并不是在传递副本。相反,第一个元素的地址被传递给函数。这就是 entrada 修改 cad 中指针的方式。

关于C语言 : args in functions inside Main (). 不清楚它们是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10556481/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com