当前位置:网站首页>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);
}
边栏推荐
- 数据归一化
- OSError: [WinError 127] 找不到指定的程序。Error loading “caffe2_detectron_ops.dll“ or one of its dependencies
- tensorflow和pytorch框架的安装以及cuda踩坑记录
- Numpy cheatsheet
- Target detection tagged data enhancement code
- JS star scoring effect
- GCC 中__attribute__((constructor)和__attribute__(((destructor))的注意事项。
- 如何解决训练集和测试集的分布差距过大问题
- Chapter IV decision tree summary
- Delete the weight of the head part of the classification network pre training weight and modify the weight name
猜你喜欢

Introduction to QT new project

Watermelon book / Pumpkin book -- Chapter 1 and 2 Summary
![[MYCAT] related concepts of MYCAT](/img/44/99d413d47828252267b5242c64960b.png)
[MYCAT] related concepts of MYCAT

谷歌/火狐浏览器管理后台新增账号时用户名密码自动填入的问题

用指针访问二维数组
![[MYCAT] MYCAT installation](/img/52/2f77ed64b2ed4e9297acaa8362e194.png)
[MYCAT] MYCAT installation

AD1256
![[USB host] stm32h7 cubemx porting USB host with FreeRTOS to read USB disk, usbh_ Process_ The OS is stuck. There is a value of 0xa5a5a5](/img/be/b7723920f0e81e8699bb26dd1c0fe5.png)
[USB host] stm32h7 cubemx porting USB host with FreeRTOS to read USB disk, usbh_ Process_ The OS is stuck. There is a value of 0xa5a5a5
![[MYCAT] Introduction to MYCAT](/img/26/8911fe9e1fb104d7185dda0881804b.png)
[MYCAT] Introduction to MYCAT

删除分类网络预训练权重的的head部分的权重以及修改权重名称
随机推荐
day6-jvm
Chapter III summary of linear model
JUC并发编程基础(8)--读写锁
‘Results do not correspond to current coco set‘
[USB host] stm32h7 cubemx porting USB host with FreeRTOS to read USB disk, usbh_ Process_ The OS is stuck. There is a value of 0xa5a5a5
Statistical learning methods (2nd Edition) Li Hang Chapter 22 summary of unsupervised learning methods mind mapping notes
HAL_ Delay() delay error about 1ms
Loss after cosine annealing decay of learning rate
Machine learning (zhouzhihua) Chapter 5 notes on neural network learning
Better CV link collection (dynamic update)
Draw contour cv2.findcontours function and parameter interpretation
DeepSort 总结
tensorflow和pytorch框架的安装以及cuda踩坑记录
JUC并发编程基础(9)--线程池
Detailed discussion on data synchronization tools ETL, ELT, reverse ETL
Typora installation package in November 2021, the last free version of the installation package to download v13.6.1
通道注意力与空间注意力模块
Machine learning (Zhou Zhihua) Chapter 4 notes on learning experience of decision tree
[deep learning] handwritten neural network model preservation
Chapter 5 neural network