当前位置:网站首页>函数中使用sizeof(arr) / sizeof(arr[0])求数组长度不正确的原因
函数中使用sizeof(arr) / sizeof(arr[0])求数组长度不正确的原因
2022-07-02 04:58:00 【Jimmy_jimi】
问题描述
sizeof()函数是求数组所占的内存空间大小(不是长度)。当在函数中使用该方法求数组长度时,由于数组作为函数参数传入函数的过程中会“退化”为指针,因此将会导致sizeof(arr)求出的是一个指针的内存空间大小,而非数组的内存空间大小–>从而导致计算的长度错误
//输入一个数看看数列里面有没有这个数
#include <stdio.h>
int main ()
{
int a[]={
1,2,3,4,34,455,23,4,7,1,9,6,8,};
int i=0,x,logic=0,n;
int fun(int x,int a[],int logic);
printf("请输入一个数:\n");
scanf("%d",&x);
n=fun(x,a,logic);
if(n==-1)
printf("未在数列中找到该数\n");
else{
printf("输入这个数在数列中是第%d位\n",n);
}
printf("%d\n",n);
return 0;
}
int fun(int x,int a[],int logic)
{
logic=-1;
int i;
for (i=0;i<sizeof(a)/sizeof(a[0]);i++)
{
if(x==a[i])
{
logic=i;
break;
}
}
return logic;
}
解决方案:
int main() {
int a[] = {
1,2,3,4,34,455,4,7,1,98,6 };
int len = sizeof(a) / sizeof(a[0]);
int i = 0, x, logic = 0, n;
int fun(int x, int len, int a[], int logic);
printf("please input a num: \n");
scanf("%d", &x);
n = fun(x, len, a, logic);
if (n == -1)
printf("not find");
else {
printf("at %d ", n);
}
return 0;
}
int fun(int x, int len,int a[], int logic) {
logic = -1;
for (int i = 0; i < len; i++) {
if (x == a[i]) {
logic = i;
break;
}
}
printf("%d\n", logic);
return logic;
}
边栏推荐
- List of common bugs in software testing
- 農業生態領域智能機器人的應用
- Ruby replaces gem Alibaba image
- Analyzing the hands-on building tutorial in children's programming
- C# 基于MQTTNet的服务端与客户端通信案例
- Realize the function of data uploading
- Video cover image setting, put cover images into multiple videos in the simplest way
- Thinkphp内核工单系统源码商业开源版 多用户+多客服+短信+邮件通知
- Promise all()
- Keil compilation code of CY7C68013A
猜你喜欢
Leetcode- insert and sort the linked list
06 decorator mode
Social media search engine optimization and its importance
农业生态领域智能机器人的应用
農業生態領域智能機器人的應用
Thinkphp內核工單系統源碼商業開源版 多用戶+多客服+短信+郵件通知
Summary of common string processing functions in C language
Realize the function of data uploading
Cultivate primary and secondary school students' love for educational robots
Record the bug of unity 2020.3.31f1 once
随机推荐
LM09丨费雪逆变换反转网格策略
Flag bits in assembly language: CF, PF, AF, ZF, SF, TF, if, DF, of
oracle 存储过程与job任务设置
Lm09 Fisher inverse transform inversion mesh strategy
2022-003arts: recursive routine of binary tree
fastText文本分类
Unity particle Foundation
Idea automatic package import and automatic package deletion settings
数学知识——快速幂的理解及例题
Mapping settings in elk (8) es
Go GC garbage collection notes (three color mark)
Mathematical knowledge (Euler function)
Save the CDA from the disc to the computer
Gin framework learning code
汇编语言中的标志位:CF、PF、AF、ZF、SF、TF、IF、DF、OF
geotrust ov多域名ssl證書一年兩千一百元包含幾個域名?
C - derived classes and constructors
VMware installation win10 reports an error: operating system not found
国产全中文-自动化测试软件Apifox
Keil compilation code of CY7C68013A