我在主函数中定义了一个字符串数组,我想在另一个函数中更新它,如下所示:
#include <stdio.h>
#define SIZE 15
void read_arrays(char *competitors[SIZE], float points[SIZE], int numOfCompetitors)
{
for (int cntr = 0; cntr < numOfCompetitors; cntr++)
{
printf("Enter the name of competitor %d", cntr+1);
scanf("%s", &*competitors[cntr]);
printf("Enter the point of competitor %d", cntr+1);
scanf("%f", &points[cntr]);
}
}
int main()
{
char *competitors[SIZE];
float points[SIZE];
int numOfCompetitors = 0;
while (numOfCompetitors > 15 || numOfCompetitors < 1)
{
printf("Enter the number of competitors: ");
scanf("%d", &numOfCompetitors);
if (numOfCompetitors > 15) printf("Number of competitors cannot be more than 15!\n");
}
read_arrays(&*competitors[SIZE], &points[SIZE], numOfCompetitors);
printf("%f", points[0]);
}
但我收到以下错误:
cc homework2.c -o homework2
homework2.c: In function ‘main’:
homework2.c:28:14: warning: passing argument 1 of ‘read_arrays’ from incompatible pointer type [-Wincompatible-pointer-types]
read_arrays(&*competitors[SIZE], &points[SIZE], numOfCompetitors);
^
homework2.c:5:6: note: expected ‘char **’ but argument is of type ‘char *’
void read_arrays(char *competitors[SIZE], float points[SIZE], int numOfCompetitors)
我想在循环中用scanf在字符串数组中分配值。我如何能够做到这一点?
最佳答案
您可以在将变量传递给函数时使用变量名,还需要指定char矩阵(〜字符串数组)的大小。
所以这:read_arrays(&*competitors[SIZE], &points[SIZE], numOfCompetitors);
成为:read_arrays(competitors, points, numOfCompetitors);
完整代码:
#include <stdio.h>
#define SIZE 15
void read_arrays(char competitors[SIZE][30], float points[SIZE], int numOfCompetitors)
{
for (int cntr = 0; cntr < numOfCompetitors; cntr++)
{
printf("Enter the name of competitor %d", cntr+1);
// We read up to 29 characters => no overflow as the size is up to 30
scanf("%29s", competitors[cntr]);
printf("Enter the point of competitor %d", cntr+1);
scanf("%f", &points[cntr]);
}
}
int main()
{
char competitors[SIZE][30];
float points[SIZE];
int numOfCompetitors = 0;
while (numOfCompetitors > 15 || numOfCompetitors < 1)
{
printf("Enter the number of competitors: ");
scanf("%d", &numOfCompetitors);
if (numOfCompetitors > 15) printf("Number of competitors cannot be more than 15!\n");
}
read_arrays(competitors, points, numOfCompetitors);
printf("%s", competitors[0]);
printf("%s", competitors[1]);
printf("%f", points[0]);
}
关于c - 更新C函数内部的字符串数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47611422/