当前位置:网站首页>When array is used as a function parameter, it is better to use the array size as a function parameter
When array is used as a function parameter, it is better to use the array size as a function parameter
2022-07-29 04:02:00 【Xiaowa 123】
1. A good habit : When an array is used as a function parameter , It is better to take the array size as an argument of the function .
2. If the array size is uncertain , Plus maybe the code is not written carefully , May cause array overflow ( An array ), However, the compiler does not report errors , Here's an example , This explains why it is best to specify the array length as a parameter .
This is a function that sums the array elements and calculates the average value
#include<stdio.h>
int getAvgScore(int score[])
{
int *p;
int num = 0;
int sum = 0;
p = score;
//while ((*p) != -1)
for (int i = 0; i < 5; i++)// There is a problem with the code written here , It has been retrieved sscore[4], But in fact, the array has only three elements , There is an array overflow problem , But the compiler does not report errors !
{
sum += *p;
num++;
p++;
}
return sum / num;
}
int main()
{
int score[] = { 10, 10, 10};// here -1 As the end of the array
int a = 0;
a = getAvgScore(score);
printf("a=[%d]\n", a);
return 0;
}
This result is obviously incorrect , The reason is that the size of the input parameter group is not determined , There is an array overflow problem , although score[3] The following value is no longer an array element , But it is still calculated into the program . When this kind of mistake occurs , The program can still run normally without error , But the result is wrong , This may take a lot of time to find mistakes .
therefore , To avoid this , You can use the following two methods :
1. Pass the length of the array along with the size of the array as a parameter to the function , Make a clear statement . So , Make the following changes to the program ( Take the length of the array as one of the parameters ):
#include<stdio.h>
int getAvgScore(int score[],int size)// Be careful
{
int *p;
int num = 0;
int sum = 0;
p = score;
//while ((*p) != -1)
for (int i = 0; i < size; i++)// Be careful
{
sum += *p;
num++;
p++;
}
return sum / num;
}
int main()
{
int score[3] = { 10, 10, 10 };// here -1 As the end of the array
int a = 0;
int size = sizeof(score) / sizeof(int);
a = getAvgScore(score,size);
printf("a=[%d]\n", a);
return 0;
}Results the correct , by 10.
2. If it is inconvenient to add the length of the array in the function parameter list , You can set the flag of the end of the array in the array element .( For character arrays, it is '\0',int Type array common -1 As an end sign )
#include<stdio.h>
int getAvgScore(int score[])// Be careful
{
int *p;
int num = 0;
int sum = 0;
p = score;
while (*p!=-1)// Cycle termination conditions
{
sum += *p;
num++;
p++;
}
return sum / num;
}
int main()
{
int score[] = { 10, 10, 10,-1 };// here -1 As the end of the array
int a = 0;
// int size = sizeof(score) / sizeof(int);
a = getAvgScore(score);
printf("a=[%d]\n", a);
return 0;
}The results are still correct .
in general , The purpose is to keep a good habit , Try to write code according to the specification , This is not to say that these are inevitable , But according to the specification , The procedure can be more rigorous .
边栏推荐
- How to understand clock cycle and formula CPU execution time = number of CPU clock cycles / dominant frequency
- JS cookie usage
- First knowledge of C language (3)
- The function parameters of the new features of ES6 are assigned initial values and rest parameters
- There is a special cryptology language called asn.1
- 有一种密码学专用语言叫做ASN.1
- Extended operator of new features in ES6
- Solve the problem of garbled code when opening the project code in idea
- 3. Solve pychart's error unresolved reference 'selenium' unresolved reference 'webdriver‘
- The const keyword of ES6 declares variables
猜你喜欢

Typescript from getting started to mastering (XVI) configuration file - first knowledge of compileroptions configuration item

Ssl== certificate related concepts

CUB_ Visualization of key points in 200 bird dataset

Deep understanding of browser caching mechanism (HTTP)

Nacos registry

Uni app internationalization

Deep understanding of Base64 underlying principles

Solve the problem of garbled code when opening the project code in idea

Solve the delay in opening the console of Google browser

数据挖掘——关联分析例题代码实现(下)
随机推荐
Opensql quick learning
[untitled]
Typescript from getting started to mastering (XX) function generics
华为天才少年稚晖君做了一把模块化机械键盘,引起极客圈地震,网友:这才是真正的客制化...
EMD 经验模态分解
Extended operator of new features in ES6
Pointer variables -printf%d and%p meaning
LVS+KeepAlived高可用部署实战应用
Li Kou daily question - day 44 -205. Isomorphic string
数据挖掘——关联分析基础介绍(上)
Data mining -- code implementation of association analysis example (Part 2)
数据源是SQL server ,我要配置日期字段 updateDate 最后两天日期的增量数据,做增
HCIP BGP
Lua语言(stm32+2G/4G模块)和C语言(stm32+esp8266)从字符串中提取相关数据的方法-整理
Uni app internationalization
Configmap configuration and secret encryption
VScode连接ssh遇到的问题
Typescript from getting started to mastering (19) enumeration types
C language: getchar () and cache
1985-2020 (8 Editions) global surface coverage download and introduction