当前位置:网站首页>Accessing a one-dimensional array with a pointer
Accessing a one-dimensional array with a pointer
2022-07-24 06:01:00 【Zonggu22】
List of articles
In order to find
- Pointer is required : In the set of integers r Medium order search and given value key Equal elements .
- Use a one-dimensional integer array a[n] Store integer set , The sequential search starts with the first element of the array , Compare each element in turn , Until you find key until , If all the elements of the array are compared , Description search failed
Array implementation
#include <stdio.h>
#define N 6
int main()
{
int a[N] = {
2,4,8,6,5,3 }, i, key, index = 0;
key = 8;
for(i=0;i<N;i++)
if (a[i] == key)
{
index = i;
break;
}
if (i == N)
index = -1; // Did not find
if (index == -1)
printf(" To find the failure !\n");
else
printf(" Find success , Elements %d The sequence number in the set is %d\n", key, index);
return 0;
}
Pointer implementation
#include <stdio.h>
#define N 6
int main()
{
int a[N] = {
2,4,8,6,5,3 }, i, key, index = 0;
int* p = a;
key = 8;
for (; p < a + N; p++)
if (*p == key) {
index = p - a;
break;
}
if (p == a + N)
index = -1;
if (index == -1)
printf(" To find the failure !\n");
else
printf(" Find success , Elements %d The sequence number in the set is %d\n", key, index);
return 0;
}
There are three ways to access a one bit array element
- 1、 Access array elements by subscript :
int a[10]; for (int i = 0;i < 10;i++) a[i] = i;
- 2、 Access array elements by address
int a[10]; for (int i = 0;i < 10; i++) *(a+i) = i; //a+i It's No i Elements
- 3、 Access array elements through pointers :
int a[10]; int *p=a; for (int i = 0;i < 10; i++) *(p+i)=i; //*(p+i) It can be used p[i] Instead of(a+i) and (p+i) It's different .a Can't move ,p Mobile p++ a Is the first address of the saved array , Constant pointer
p++ Self increasing operation is better than p+i Arithmetic is much faster , Therefore, its execution efficiency is higher than that of address mode
int a[10]; int *p = a; for (int i = 0; p < (a+10); i++,p++) // expression 3 It's a comma expression *p=i;
Because the array occupies a continuous memory space , therefore , The arithmetic operation of pointers is usually used for arrays .
int num,a[5]={
1,2,3,4,5};
int *p=a,*q; // The pointer p Point to elements a[0]
q=p+4; // amount to q = p + 4 × sizeof(int), take q Point to a[4]
num=q-p; // The pointer q and p The number of elements between , The value is 4
num=(int)q-(int)p; // The pointer q and p The number of bytes between , The value is 16( This is rarely used )
Relational operation of pointer variables
Compare pointers of the same type .
Between different types of pointers 、 Pointer and non 0 The relation operation between integers has no practical significance .
hypothesis p and q Are two pointer variables of the same type , be
- p == q: Judgment pointer p and q Whether to point to the same storage unit
- p > q : The pointer p The storage unit referred to is in the pointer q Behind the storage unit
- p != NULL : Judgment pointer p Null pointer or not
Cited example
Input 10 It's an integer , Exchange the smallest number with the first number , Exchange the largest number with the last number .
- Example of program running results ( Blue font indicates input ):
- Please enter 10 It's an integer :2 3 4 23 5 78 0 1 6 12
- The result of the exchange is :0 3 4 23 5 12 2 1 5 78
- Please enter 10 It's an integer :1 25 7 40 5 6 12 8 30 19
- The result of the exchange is :1 25 7 19 5 6 12 8 30 40
The above program is realized by array, that is, array parameter transfer .
Write 3 A function :(1) Input 10 Number ;(2) To deal with ;(3) Output 10 Number .
This program uses array and pointer to realize .
Array implementation
// In general, we seldom pass an array parameter directly , It is often necessary to pass two parameters , It's an array , How long is the second transmission group
void process(int arr[],int num)
{
int temp;
int maxNum = arr[0];
int minNum = arr[0];
int maxPos = 0;
int minPos = 0;
for (int i=1; i<num; i++)
{
if (arr[i] < minNum)
{
minNum = arr[i];
minPos = i;
}
if (arr[i] > maxNum)
{
maxNum = arr[i];
maxPos = i;
}
}
// If the minimum number is not the first number , Exchange the minimum number with the first number
if (minPos != 0)
swap(&arr[0],&arr[minPos]);
// If the maximum number is not the last number , Exchange the maximum number and the last number
if (maxPos != num-1)
swap(&arr[num-1],&arr[maxPos]);
}
The main function
int main()
{
int a[10];
inputArray(a,10);
process(a,10);
outputArray(a,10);
return 0;
}
Pointer implementation
void process(int *arr,int num)
{
int temp;
int *p; //p The pointer moves backward to scan the array
int *min,*max; //min and max The pointer records the minimum and maximum addresses
p=max=min=arr; //p,max,min Both point to the first number of the array
for (; p<arr+num ; p++)
{
if (*p<*min)
min = p;
if (*p>*max)
max = p;
}
if (min != arr)
swap(arr,min);
if (max != arr+num-1)
swap((arr+num-1),max);
}
The main function
// Call statement
process(a,10);
One dimensional array as a function parameter
The characteristics of seat parameters of one-dimensional array are : Parameter array and argument array are the same array .
in other words , The main program and subroutine have different names , Shared the same space . So in the subroutine , adopt arr【i】 Any changes to the array , Will correspondingly affect the corresponding arguments a【i】
The practical application
describe
There are multiple consecutive spaces in a sentence , Filter extra spaces , Just leave a space .
Input
a line , A string ( Length not exceeding 200), There are no spaces at the beginning and the end of a sentence
Output
Filtered sentences
The sample input :
Hello world.This is c language.
Sample output
Hello world.This is c language.
| str1: | T | h | i | s | i | s | c | l | a | n | g | u | a | g | e | \0 |
|---|
| str2: | T | h | i | s | i | s | c | l | a | n | g | u | a | g | e | \0 |
|---|
void operate(char *p1,char *p2)
{
while (*p1)
{
if (*p1!=' ')
{
*p2++=*p1++; //* Priority of
}
else
{
*p2++ = ' ';
while(*p1 == ' ')
p1++;
/* It can also be written as while (*p1++ == ' ') ; */
}
}
*p2 = '\0'; // hold str2 Initialize to '\0' There is no need to write this , Considering that other situations will be used , May not initialize , Plus this will be very safe
}
int mian()
{
char str1[201]={
0};
char str2[201]={
0};
gets(str1);
operate(str1,str2);
printf("%s",str2);
}
边栏推荐
- Typora installation package in November 2021, the last free version of the installation package to download v13.6.1
- 找数组中出现次数最多的数
- [MYCAT] MYCAT configuration file
- Statistical learning methods (2nd Edition) Li Hang Chapter 22 summary of unsupervised learning methods mind mapping notes
- labelme转voc代码中的一个小问题
- PyTorch 单机多卡分布式训练
- PDF文本合并
- 《剑指Offer》 二维数组的查找 C语言版本
- 【数据库系统原理】第四章 高级数据库模型:统一建模语言UML、对象定义语言ODL
- 传统的k-means实现
猜你喜欢
![[FatFs] migrate FatFs manually and transfer SRAM virtual USB flash disk](/img/fb/5f3d17f1f3d6e4979ece5126e2925e.png)
[FatFs] migrate FatFs manually and transfer SRAM virtual USB flash disk
![[MYCAT] MYCAT configuration file](/img/53/63a633d3ae917e3754f9f7f5c6567f.png)
[MYCAT] MYCAT configuration file

单播、组播、广播、工具开发、QT Udp通讯协议开发简介及开发工具源码
![[activiti] group task](/img/f1/b99cae9e840d3a91d0d823655748fe.png)
[activiti] group task

STM32 DSP library MDK vc5\vc6 compilation error: 256, (const float64_t *) twiddlecoeff64_ 256, armBitRevIndexTableF64_ 256,

JUC并发编程基础(8)--读写锁

day-7 jvm完结

《统计学习方法(第2版)》李航 第14章 聚类方法 思维导图笔记 及 课后习题答案(步骤详细) k-均值 层次聚类 第十四章

Deepsort summary
![[raspberry pie 4B] VII. Summary of remote login methods for raspberry pie xshell, putty, vncserver, xrdp](/img/dc/364fdc4c1748cc5522e4592bc47dc3.png)
[raspberry pie 4B] VII. Summary of remote login methods for raspberry pie xshell, putty, vncserver, xrdp
随机推荐
MySql下载,及安装环境设置
In GCC__ attribute__ ((constructor) and__ attribute__ ((destructor)).
《统计学习方法(第2版)》李航 第16章 主成分分析 PCA 思维导图笔记 及 课后习题答案(步骤详细)PCA 矩阵奇异值 第十六章
Qt 使用纯代码画图异常
JUC并发编程基础(4)--线程组和线程优先级
STM32 DSP library MDK vc5\vc6 compilation error: 256, (const float64_t *) twiddlecoeff64_ 256, armBitRevIndexTableF64_ 256,
AD1256
Machine learning (zhouzhihua) Chapter 1 Introduction notes learning experience
主成分分析计算步骤
Iotp2pgate two IOT devices point-to-point communication fast implementation scheme
《统计学习方法(第2版)》李航 第14章 聚类方法 思维导图笔记 及 课后习题答案(步骤详细) k-均值 层次聚类 第十四章
单播、组播、广播、工具开发、QT Udp通讯协议开发简介及开发工具源码
Deepsort summary
[activiti] personal task
[activiti] group task
Jupyter notebook选择conda环境
Qt新手入门级 计算器加、减、乘、除、应用
PDF文本合并
【树莓派4B】七、远程登录树莓派的方法总结XShell,PuTTY,vncServer,Xrdp
Watermelon book / Pumpkin book -- Chapter 1 and 2 Summary