C: language related tips

1. The relationship between arrays and linked lists

Arrays and linked lists are both linear list data structures.

Second, the difference between arrays and linked lists

1. Arrays can be accessed randomly and sequentially, while linked lists can only be accessed sequentially.

2. Arrays allocate memory statically, and linked lists dynamically allocate memory.

3. An array is a linear table data structure with a set of continuous memory spaces. A linked list is a data structure used to connect a set of scattered memory blocks in series through pointers, and does not require a continuous memory space.
—————————————————————————————————————————————

  • In C language, arrays and subscripts can be interchanged, which is determined by the pointer definition of array subscripts. Due to the existence of the law of addition and commutation, as long as one is a pointer and the other is an integer, it does not matter the order, a[3], etc. Equivalent to 3[a], equivalent to *(a+3), equivalent to *(3+a).

  •  Find the number of array elements: j = sizeof(a) / sizeof a[0];
  • Modify the address pointed to by the pointer

  •  structure

 

struct Student s1;

struct Student * p = &s1;

p→xx == (*p).xx (*p).xx==s1.xx so p→xx==s1.xx

  • Static variables and dynamic variables: Variables allocated using malloc() are dynamic (memory of different sizes can be applied for or destroyed when the program is running), otherwise they are static (allocated when the program is running and will be destroyed after the program runs).  

The address of the first byte is regarded as an integer address. The so-called integer address represents the address of the first byte is the address representing four bytes.

 [] ==*()

→==(*).

3. Variable naming rules

Fourth, the usage of sscanf

Read and parse a line of GPS raw data

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>
#include <stdlib.h>

/* set_opt(fd,115200,8,'N',1)  串口参数的设置*/  
int set_opt(int fd,int nSpeed, int nBits, char nEvent, int nStop)
{
	struct termios newtio,oldtio;
	
	if ( tcgetattr( fd,&oldtio) != 0) { 
		perror("SetupSerial 1");
		return -1;
	}
	
	bzero( &newtio, sizeof( newtio ) );
	newtio.c_cflag |= CLOCAL | CREAD; 
	newtio.c_cflag &= ~CSIZE; 

	newtio.c_lflag  &= ~(ICANON | ECHO | ECHOE | ISIG);  /*Input*/
	newtio.c_oflag  &= ~OPOST;   /*Output*/

	switch( nBits )
	{
	case 7:
		newtio.c_cflag |= CS7;
	break;
	case 8:
		newtio.c_cflag |= CS8;
	break;
	}

	switch( nEvent )
	{
	case 'O':
		newtio.c_cflag |= PARENB;
		newtio.c_cflag |= PARODD;
		newtio.c_iflag |= (INPCK | ISTRIP);
	break;
	case 'E': 
		newtio.c_iflag |= (INPCK | ISTRIP);
		newtio.c_cflag |= PARENB;
		newtio.c_cflag &= ~PARODD;
	break;
	case 'N': 
		newtio.c_cflag &= ~PARENB;
	break;
	}

	switch( nSpeed )
	{
	case 2400:
		cfsetispeed(&newtio, B2400);
		cfsetospeed(&newtio, B2400);
	break;
	case 4800:
		cfsetispeed(&newtio, B4800);
		cfsetospeed(&newtio, B4800);
	break;
	case 9600:
		cfsetispeed(&newtio, B9600);
		cfsetospeed(&newtio, B9600);
	break;
	case 115200:
		cfsetispeed(&newtio, B115200);
		cfsetospeed(&newtio, B115200);
	break;
	default:
		cfsetispeed(&newtio, B9600);
		cfsetospeed(&newtio, B9600);
	break;
	}
	
	if( nStop == 1 )
		newtio.c_cflag &= ~CSTOPB;
	else if ( nStop == 2 )
		newtio.c_cflag |= CSTOPB;
	
	newtio.c_cc[VMIN]  = 1;  /* 读数据时的最小字节数: 没读到这些数据我就不返回! */
	newtio.c_cc[VTIME] = 0; /* 等待第1个数据的时间: 
	                         * 比如VMIN设为10表示至少读到10个数据才返回,
	                         * 但是没有数据总不能一直等吧? 可以设置VTIME(单位是10秒)
	                         * 假设VTIME=1,表示: 
	                         *    10秒内一个数据都没有的话就返回
	                         *    如果10秒内至少读到了1个字节,那就继续等待,完全读到VMIN个数据再返回
	                         */

	tcflush(fd,TCIFLUSH);
	
	if((tcsetattr(fd,TCSANOW,&newtio))!=0)  //设置行规程
	{
		perror("com set error");
		return -1;
	}
	//printf("set done!\n");
	return 0;
}

int open_port(char *com)
{
	int fd;
	//fd = open(com, O_RDWR|O_NOCTTY|O_NDELAY);
	fd = open(com, O_RDWR|O_NOCTTY);  //O_RDWR可读可写  O_NOCTTY不要把单做控制台
    if (-1 == fd){
		return(-1);
    }
	
	  if(fcntl(fd, F_SETFL, 0)<0) /* 设置串口为阻塞状态  	1.fcntl ( fd, FSETFL,FNDELAY);
															读数据时不等待,没有数据就返回0
															2.fcntl(FD,F_SETFL,O);
															读数据时,没有数据阻塞  


*/
	  {
			printf("fcntl failed!\n");
			return -1;
	  }
  
	  return fd;
}

/* 读一行GPS原始数据*/
/* eg. $GPGGA,082559.00,4005.22599,N,11632.58234,E,1,04,3.08,14.6,M,-5.6,M,,*76"<CR><LF> */
/* <CR><LF>	回车换行*/
int read_gps_raw_data(int fd, char *buf)
{
	int i = 0;
	int iRet;
	char c;
	int start = 0;
	
	while (1)
	{
		iRet = read(fd, &c, 1); //读一个数据保存的c
		if (iRet == 1)
		{
			if (c == '$')		//判断第一个字符是否为数据起始符$
				start = 1;
			if (start)
			{
				buf[i++] = c;
			}
			if (c == '\n' || c == '\r')
				return 0;
		}
		else
		{
			return -1;
		}
	}
}
/*解析数据*/
/* eg. $GPGGA,082559.00,4005.22599,N,11632.58234,E,1,04,3.08,14.6,M,-5.6,M,,*76"<CR><LF> */
int parse_gps_raw_data(char *buf, char *time, char *lat, char *ns, char *lng, char *ew)
{
	char tmp[10];
	
	if (buf[0] != '$')
		return -1;
	else if (strncmp(buf+3, "GGA", 3) != 0)  //字串相比较
		return -1;
	else if (strstr(buf, ",,,,,")) //strstr 查找数据中是否有,,,,,这样连续的字符串
	{
		printf("Place the GPS to open area\n"); 
		return -1;
	}
	else {
		//printf("raw data: %s\n", buf);
		sscanf(buf, "%[^,],%[^,],%[^,],%[^,],%[^,],%[^,]", tmp, time, lat, ns, lng, ew);
		 //将原始数据的buf中的字符串存到指定的buf中(从字符串读取格式化输入)
		 //[^,]scanf的高级用法,^表示剔除不包含,[^,]表示遇到,就停止
		return 0;
	}
}


/*
 * ./serial_send_recv <dev>
	argv[1] 传入的是设备节点
 */
int main(int argc, char **argv)
{
	int fd;  	
	int iRet;
	char c;
	char buf[1000];
	char time[100];
	char Lat[100]; 
	char ns[100]; 
	char Lng[100]; 
	char ew[100];

	float fLat, fLng;

	/* 1. open */

	/* 2. setup 
	 * 115200,8N1
	 * RAW mode
	 * return data immediately
	 */

	/* 3. write and read */
	
	if (argc != 2)
	{
		printf("Usage: \n");
		printf("%s </dev/ttySAC1 or other>\n", argv[0]);
		return -1;
	}

	fd = open_port(argv[1]);
	if (fd < 0)
	{
		printf("open %s err!\n", argv[1]);
		return -1;
	}

	iRet = set_opt(fd, 9600, 8, 'N', 1);
	if (iRet)
	{
		printf("set port err!\n");
		return -1;
	}

	while (1)
	{
		/* eg. $GPGGA,082559.00,4005.22599,N,11632.58234,E,1,04,3.08,14.6,M,-5.6,M,,*76"<CR><LF>*/
		/* read line */
		iRet = read_gps_raw_data(fd, buf);
		
		/* parse line */
		if (iRet == 0)
		{
			iRet = parse_gps_raw_data(buf, time, Lat, ns, Lng, ew);
		}
		
		/* printf */
		if (iRet == 0)
		{
			printf("Time : %s\n", time);
			printf("ns   : %s\n", ns);
			printf("ew   : %s\n", ew);
			printf("Lat  : %s\n", Lat);
			printf("Lng  : %s\n", Lng);

			/* 纬度格式: ddmm.mmmm */
			sscanf(Lat+2, "%f", &fLat);
			fLat = fLat / 60;  //分化成度
			fLat += (Lat[0] - '0')*10 + (Lat[1] - '0');  //字符减去字符‘0’就等于数值

			/* 经度格式: dddmm.mmmm */
			sscanf(Lng+3, "%f", &fLng);
			fLng = fLng / 60;
			fLng += (Lng[0] - '0')*100 + (Lng[1] - '0')*10 + (Lng[2] - '0');
			printf("Lng,Lat: %.06f,%.06f\n", fLng, fLat);
			//%.06f 小数点后保存6位
		}
	}

	return 0;
}

C library function – sscanf() | Novice Tutorial

5.define tag

In-depth understanding of #define preprocessing, preprocessor operator# ## #@_梦起周's Blog-CSDN Blog_Preprocessor Operator

Special Arguments in Macro Definitions (#, ##, ... and __VA_ARGS__) - Baidu Library

6. Add, delete, check and modify array linked list address book practice

Reference article:  C language realizes dynamic address book (with file storage)_rivencode's blog-CSDN blog

Search Results for qsort

7. Excellent blog posts

7.1 File reading and writing

Detailed explanation of file operation in c language - rivencode's blog - CSDN blog

It is enough to read this article for a detailed explanation of the strerror function - C language (function explanation, usage example, function) - Quack Roast Duck's Blog - CSDN Blog

Pointers from entry to proficiency_rivencode's Blog-CSDN Blog

Custom Type - Detailed Explanation of Structure_rivencode's Blog-CSDN Blog_Custom Structure

C language preprocessing instructions - necessary skills for microcontrollers - rivencode's blog - CSDN blog

<C/C++ Memory Management>——"C++ Elementary"_Xinxiao·Old Knowledge (Entrance Examination Stopped) Blog-CSDN Blog

https://blog.csdn.net/DlMmU/article/details/79799191

In-depth analysis of static, const, volatile, extern, register keywords - rivencode's blog - CSDN blog

C language is different from C++, why can't const define the size of an array in C language?

The difference between declaration and definition

lv_obj_add_state(sw, chk ? LV_STATE_CHECKED : 0); // add event

7.2 The switch selection not only corresponds to numbers but also characters, but there are problems.

In-depth understanding of time and space complexity_The concept of time complexity and space complexity_rivencode's blog-CSDN blog

Realization of dynamic memory allocation and dynamic sequence table - rivencode's blog - CSDN blog

The return value of malloc must be checked.
When using realloc to reallocate space, you must first take a temporary pointer to receive the return value. You cannot directly use the pointer of the original space to receive the return value. If realloc fails to allocate space, it will return a NULL and directly use the original space. If the pointer is used to receive it, the original space will not be found directly.
How to avoid wild pointers
1. Pointer initialization
2. Be careful that the pointer is out of bounds
3. The pointer points to the space to release even if it is set to NULL
4. Avoid returning the address of the local variable
5. Check the validity of the pointer before using it  

How is the data of deep anatomy of C language stored in memory - rivencode's blog - CSDN blog

Integer promotion, arithmetic conversion, storage and retrieval of variable contents

C language linked list super detailed explanation_linked list c language_rivencode's blog-CSDN blog

Detailed explanation of C language operators - rivencode's blog - CSDN blog

Implementation of C language stack and queue - rivencode's Blog - CSDN Blog

C language implementation stack_哔哩哔哩_bilibili

 

23.3.8

C language pointer advanced - rivencode's blog - CSDN blog

Simulation implementation of qsort function and qsort function_哔哩哔哩_bilibili

qsort() function and bsearch() function_哔哩哔哩_bilibili

(70 messages) C language pointer interview questions-1_*--*++cpp+3_HZCVinter's Blog-CSDN Blog

Detailed explanation and simulation implementation of string and memory operation functions_source string and destination string_rivencode's blog-CSDN blog

08_strtok string cutting function_哔哩哔哩_bilibili

The formation and release of function stack frames - rivencode's blog - CSDN blog

Brush questions on Niuke.com - merge two ordered arrays_Merge ordered sequences on Niuke.com_rivencode's blog-CSDN blog ​Standard library- inttypes.h - 《Ruan Yifeng "C Language Tutorial"" - 书栈网· BookStack

 UNUSED parameter, this macro is very beautiful - Zhihu (zhihu.com)

Niuke brush question-ring linked list_rivencode's blog-CSDN blog Niuke net brush question-merge two sorted linked lists_data structure merge and sort two linked lists_rivencode's blog-CSDN blog

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param element int整型 
 * @return 无
 *
 * C语言声明定义全局变量请加上static,防止重复定义
 */
#include <stdio.h>
#include <stdlib.h>
typedef int QDataType ;

typedef struct QueueNode
{
    struct QueueNode * next;
    QDataType data;
} QNode;
typedef struct Queue
{
    QNode * head;
    QNode * tail;
} Queue;

void QueueInit(Queue * pq)
{
    if(pq == NULL){
        return ;
    }
    pq->head = pq->tail =NULL;
}
void QueueDestory(Queue * pq)
{
    if(pq == NULL){
        return;
    }
    QNode * cur = pq->head;
    while (cur) {
        QNode * next = cur->next;
        free(cur);
        cur = next;
    }
    pq->head = pq->tail =NULL;
}
void QueuePush(Queue * pq , QDataType data)
{
    if (pq == NULL) {
        return;
    }
    QNode * NewNode = (QNode *)malloc(sizeof(QNode));
    if(NewNode == NULL)
    {
        printf("malloc fail\n");
        exit(-1);
    }
    NewNode->data = data;
    NewNode->next = NULL;
    if(pq -> tail == NULL)
    {
        pq->head = pq->tail = NewNode;
    }
    else {
        pq->tail->next = NewNode;
        pq ->tail = NewNode;
    }
}
void QueuePop(Queue * pq)
{
    if (pq == NULL) {
        return;
    }
    if(pq->head->next == NULL){
        free(pq->head);
        pq->head = pq->tail = NULL;
    }
    else {
        QNode * next = pq->head->next;
        free(pq->head);
        pq->head = next;
    }
}
QDataType QueueFront(Queue * pq)
{
    if (pq == NULL) {
        exit(-1);
    }
    return pq->head->data;
}
QDataType QueueBack(Queue * pq)
{
    if (pq == NULL)
    {
        exit (-1);
    }
    return pq->tail->data;
}

int QueueSize(Queue * pq)
{
    if (pq == NULL) {
        exit(-1);
    }
    int count = 0;
    QNode * cur = pq->head;
    while (cur) {
        cur = cur->next;
        count++;
    }
    return count;
}
bool QueueEmpty(Queue *pq)
{
    return pq->head == NULL;
}

Queue q1,q2;

void push(int element) {
    if(!QueueEmpty(&q1))
    {
        QueuePush(&q1, element);
    }
    else {
        QueuePush(&q2,element);
    }
}

int pop() {
    /*判断出非空队列与空队列*/
    Queue * EmptyQueue = &q1;
    Queue * NonEmptyQueue = &q2;

    if (!QueueEmpty(&q1)) {
        NonEmptyQueue = &q1;
        EmptyQueue = &q2;
    }
    //倒腾数据:非空队列往空队列里面倒腾数据(最后一个元素不动)
    while (QueueSize(NonEmptyQueue)>1)
    {
        QueuePush(EmptyQueue,QueueFront(NonEmptyQueue));
        QueuePop(NonEmptyQueue);
    }
    //出栈最后一个元素
    int top = QueueFront(NonEmptyQueue);
    QueuePop(NonEmptyQueue);
    return top;
}

int top() {
    if(!QueueEmpty(&q1)){
        return QueueBack(&q1);
    }
    else {
        return QueueBack(&q2);
    }
}

bool empty() {
    return QueueEmpty(&q1)&&QueueEmpty(&q2);
}

(87 messages) Niuke.com-"C language hundred questions" first issue_Niuke.c language question bank_rivencode's blog-CSDN blog Niuke.com-" C language hundred questions" third issue_rivencode's Blog-CSDN Blog Niuke.com-"C Language Hundred Questions" Issue 4_Niuke.com C Language Question Bank_rivencode's Blog-CSDN Blog Niuke.com- "C Language Hundred Questions" Issue 5_@rivencode's Personal homepage_rivencode's blog-CSDN blog

Guess you like

Origin blog.csdn.net/qq_45803449/article/details/128089592