【发布时间】:2020-04-21 01:10:19
【问题描述】:
有没有办法,我可以使用 strlen() 来查找数组的长度,而不是在循环中指定。 第一个代码:使用 x 这是 temps[4] 数组的大小。
#include <stdio.h>
#include <string.h>
int main(){
float temps[4] = {72.5, 73.4, 74.7, 75.2};
int x;
printf("Local Temperatures\n");
for(x = 1; x < 4; x++){
printf("Station %d: %.1f\n",x,temps[x]);
}
}
我的第二个代码,不工作,但看看什么,我试图用 strlen() 来找到数组的大小。:
#include <stdio.h>
#include <string.h>
int main(){
float temps[4] = {72.5, 73.4, 74.7, 75.2};
int x;
float size;
size = temps;
printf("Local Temperatures\n");
for(x = 1; x < strlen(size); x++){
printf("Station %d: %.1f\n",x,size[x]);
}
}
【问题讨论】:
-
strlen用于字符串。为什么你认为它适用于任何其他数组类型?要获取数组元素的数量,请执行sizeof temps / sizeof temps[0]. -
如果您启用所有编译器警告,您的编译器会输出什么?你需要这样做。您正在尝试做的事情尚不清楚,而且它不是正确的 C 代码。
-
1.
strlen仅适用于 char* 您不能将其用于数组。 2. temps 只能从 0 到 3 进行索引,数组越界访问发生在您的 sn-p -
提示:
float temps[] = ...;优于float temps[4] = ...;
标签: c