Basic Chapter 4 of C Language

Keywords: Programming

1. Custom function for finding array length.

int My_strlen(char *src)
{
	int len = 0;
	while(*src++ != '\0')
	{
		len++;
		}
	return len;
	}

2. Customize strcpy function.

(1)
void My_strcpy(char *dest,const char *src)//j plus const prevents the original string from being modified
{
    assert(dest != NULL && src != NULL);//Assertion
    	int i = 0;
	for(i = 0;src[i] != '\0';i++) 
	{
		dest[i] = src[i];//*(src+i)
	}
	dest[i] = '\0';//Manual assignment'\0'
}
(2)
void My_strcpy2(char *dest,const char *src)
{
	assert(dest != NULL && src != NULL);
	while(*src != '\0')
	{
		*dest = *src;
		dest++;//dest+1
		src++;//src+1
	}
	*dest = '\0';
}
(3)
void My_strcpy3(char *dest,const char *src)
{
	assert(dest != NULL && src != NULL);
	while(*dest++ = *src++)//Finally, the value of the while expression is 0, and the loop cannot go in, but it has been assigned.
	 {
	 }
	 }

(4)
char * My_strcpy4(char *dest,const char *src)
{
	char *p = dest;//Protect dest
	assert(dest != NULL && src != NULL);
	while(*dest++ = *src++) {}
	return p;//Return value is pointer
}
int main()
{
    char *str2 = "hello";
	char str3[6] = {};
	char *p = My_strcpy4(str3,str2);//String copy function
	printf("%s\n",p);
	return 0;
}

3. Delete even numbers in character arrays

int Fun(int *arr,int len)
{
	int j = 0;//Subscription of odd numbers
	for(int i = 0;i < len;i++) 
	{
		if(arr[i] % 2 != 0) //Odd number
		{
			arr[j] = arr[i];
			j++;
		}
	}
	return j;
}

IV. Judgment of Size and Size

bool IsBig()
{
	int a = 0x12345678;
	char *p = (char *)&a;//p pointer can only access one byte
	if(*p == 0x78) 
	{
		return false;//Small end
	}
	else
	{
		return true;//Big end
	}
}

Five.
char *str="hello";
char *str2="hello";
printf("%d,%d",str,str2);// two values are equal, equivalent to two pointers pointing to the same string of rodata segments at the same time.
Six.
int a[10]={1,2,3};
a+sizeof(int) / / equivalent to & a [4]
&a[0]+1// Equivalent to & a[1]
(int *) & A + 1// plus 1 equals adding 4 bytes to the address of a[1].
(int*) ((char*a+sizeof(int)// sizeof(int) has a value of 4, char*a+sizeof(int) has four bytes added, and then is strongly converted to (int*) type, pointing to the address of a[1].
7. Attention should be paid to calling copy function

#include<stdio.h>
#include<string.h>
int main()
{
	char *str="tulun";
	char *str2="hello";
	char str3[5]={};
	printf("%s",strcpy(str3,str2));//Error (print first, then report), "hello" string length is 6, str3 array length is 5, cross-border
	return 0;
}

8. Size End and Size End

  • Big end: low address, high data
  • Small end: low address, low data

Posted by Magestic on Mon, 28 Jan 2019 03:33:14 -0800