[英]C - Why does my string return Null when sending it to a function?
I am a total beginner, but I am doing a project for school and I just can't seem to get it working.我是一个初学者,但我正在为学校做一个项目,但我似乎无法让它发挥作用。
The goal is simple: scan 5 strings, count their vowels and then sort it alphabetically using functions.目标很简单:扫描 5 个字符串,计算它们的元音,然后使用函数按字母顺序对其进行排序。
I have the vowel part sorted out, but when I send the already scanned strings to my function, it gets read as null so I can't sort it there.我已经整理了元音部分,但是当我将已经扫描的字符串发送到我的 function 时,它被读取为 null,所以我无法在那里对其进行排序。
I'll show you the code very simplified so I can highlight the problem more easily (without the bubble sort):我将向您展示非常简化的代码,以便我可以更轻松地突出显示问题(没有冒泡排序):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char abc(char nombres[])
{
printf("\n%s", nombres[3]);
}
int main()
{
char nombres[20][20];
printf("Ingrese 5 nombres:\n")
for (int i = 0; i < 5; i++)
{
scanf(" %s", nombres[i]);
}
abc(nombres);
return 0;
}
In my imagination, it should display the third input that was scanned, but the output reads:在我的想象中,它应该显示被扫描的第三个输入,但 output 显示:
Ingrese 5 nombres
juan
alberto
lautaro
milo
beatriz
(Null)
Hopefully, you have already spotted the problem, if so, please help me correct my code.希望您已经发现了问题,如果是,请帮助我更正我的代码。 I can send the rest if you want, I just trimmed it for the sake of simplicity.
如果您愿意,我可以发送 rest,为了简单起见,我只是对其进行了修剪。
What you're passing to the function isn't compatible with the parameter type.您传递给 function 的内容与参数类型不兼容。
The function expects a parameter of type char []
, which as a function parameter is exactly the same as char *
. function 需要一个
char []
类型的参数,作为 function 参数与char *
完全相同。 What you're passing to it is a char [20][20]
.你传递给它的是一个
char [20][20]
。 Your compiler should have warned you about this.你的编译器应该已经警告你了。 It should also have warned you about sending
nombres[3]
inside of abc
which has type char
, ie a single char
and not a string like the %s
format specifier expects.它还应该警告您在
abc
内部发送具有char
类型的nombres[3]
,即单个char
而不是%s
格式说明符所期望的字符串。
You need to change the parameter type to the function to match what you're passing to it and how you're using it.您需要将参数类型更改为 function 以匹配您传递给它的内容以及您如何使用它。
char abc(char nombres[20][20])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.