Pointer and string (to be continued)

1, Pointer

1. Primary pointer:

It is usually used as the input parameter of the function. Because the primary pointer is used as the function parameter, the actual parameter and formal parameter are different memory spaces when calling. However, the pointer stored in this memory space points to the same address, so the formal parameter can access the memory space pointed to by the actual parameter during function execution, but the change of the direction of the formal parameter cannot affect the actual parameter.

The first level pointer is used as a function parameter, and the redirection of formal parameters in the function will not affect the pointing of actual parameters.

//Application of primary pointer

void Swap(int* p,int* q) 
{
	int temp = *p; //a
	*p = *q;
	*q = temp;	
}
int main()
{	
int a = 10;
int b = 20;
Swap(&a, &b);  // Stack frame development fallback problem - > function call
printf("Value after exchange:%d %d\n", a, b);
}

2. Relationship between pointer and array

int CicleNum(int* arr,int len) 
{
	assert(arr != NULL);
	int left = len;// Number of people remaining
	int count = 0;//  Count NUM exit
	int res = -1;// Returns the number of the remaining person
	for (int i = 0;left > 1; i = ++i % len)
	{
		if (*(arr+i) != -1) {  //arr[i]
			count++;
		}
		if (count == NUM) {  // People who count NUM quit
			*(arr + i) = -1;
			count = 0;
			left--;
		}
	}
	for (int i = 0; i < len; i++) {
		if (*(arr + i) != -1) {
			res = *(arr + i);//arr[i]
		}
	}
	return res;
}

int main()
{
	Money(85);
	int arr[] = {1,2,3,4,5,6,7,8,9,10}; 
	printf("%d  ",CicleNum(arr, 10));
}



Array and pointer relationships:(p+i) <==> &p[i]
      const char *str = "hello"; 
     *(str+i) = 'z';//error
     *(str+i)  -> str[i]
 
      char arr[] = "hello";
*     arr[0] = 'z';//right

Array arr [] in   Degenerate to pointer * arr in CicleNum()

(1) Array: an array is a collection used to store multiple data of the same type.

(2) Pointer: pointer is equivalent to a variable, but it is different from different variables. It stores the addresses of other variables in memory

difference:

1) Pointer variables of the same type can be assigned to each other, but not to arrays. Only one element can be assigned or copied;

2) Arrays are stored continuously in memory, opening up a continuous memory space. Arrays are accessed according to the of arrays. Multidimensional arrays are stored in memory according to one-dimensional arrays, but logically they are multidimensional;

3) Pointers can point to any type of data. The type of pointer indicates the memory of the address space it points to.

3.const and pointer combination

1. Pointer and const Use of
 1)  
	int a = 10;
	int b = 20;
	const int* p = &a;   -> The value pointing to the variable cannot be modified
	*p = 100;//error
	p = &b; //right
	*p = 200;//error 
 
 2) 
	int a = 10,b=20;
	int*  const p = &a;   
		-> Modifies the pointer variable itself. Once pointed a,Cannot point to another address. 
			No limit a Is the value of itself modified
	p = &b;//error
	*p = 100;//right

 3)
   const int a = 10; // a constant variable
   int* p = &a;  //error    *p = 10;  error
   const int* p = &a;//right
 
 4)
  const int* const p = &a;  // p points to a and cannot point to other variables. p cannot modify the value of A

4. Definition and characteristics of string

  1) char ch[] = "hello"; //"hello" stores the array size 5 + 1 '\ 0' in the form of a character array
  2) char *p = "hello"; //String constant "hello" / / error
     const char* str = "hello";   //right
  3)char str[5];
        scanf("%s",str); 
  4)char str[5];gets(str); 

5. String related operations

strcpy(p, p1) copies the string  
strncpy(p, p1, n) copies a string of the specified length  
strcat(p, p1) additional string  
strncat(p, p1, n) appends a string of the specified length  
strlen(p) takes the length of the string  
strcmp(p, p1) compare strings  
strcasecmp ignores case comparison strings
strncmp(p, p1, n) compares strings of specified length  
strchr(p, c) finds the specified character in the string  
strrchr(p, c) looks up the string in reverse  
strstr(p, p1) lookup string  
strpbrk(p, p1) takes all characters of the target string as a set and finds any element of the set in the current string  
strspn(p, p1) takes all characters of the target string as a set, and finds the offset of any element that does not belong to the set in the current string  
strcspn(p, p1) takes all characters of the target string as a set and finds the offset of any element belonging to the set in the current string   
*The string handler with the specified length fills the zero terminator after the processed string  

(1) strlen(p) takes the length of the string

Basic understanding of string
int main()
{
	char ch[] = {'h','e','l','l','o'}; //5
	char arr[] = "he\0llo"; //7 end tag of string '\ 0'
	arr[0] = 's';
	int len_ch = sizeof(ch) / sizeof(ch[0]);
	int len_arr = sizeof(arr) / sizeof(arr[0]);

	int len_string = strlen(arr); //Number of characters before the first '\ 0'
	//2
	printf("ch:%d   arr:%d   String length%d\n",len_ch,len_arr,len_string);
	return 0;


char arr[] = {'h','e','l','l','o'};
* arr -> sizeof(arr)/sizeof(arr[0]);   //5 
* strlen(arr);  //5

(2) strcmp(p, p1) compare strings  

         strcmp(const char*str1,const char*str2);  // Compare size function

// Method 1: operate in the form of array - need to be optimized
int my_strcmp1(const char* str1,const char* str2) {
    assert(str1!=NULL && str2 != NULL);
    int len = strlen(str1);
    for (int i = 0; i <= len; i++) {
        if (str1[i] == str2[i]) {
            continue;
        }
        else if (str1[i] > str2[i]) {
            return 1;
        }
        else {
            return -1;
        }
    }
    return 0;
}

int my_strcmp1(const char* str1, const char* str2) {
    assert(str1 != NULL && str2 != NULL);
    int result = 0; 
    int len = strlen(str1);
    for (int i = 0;i <= len ; i++) {
        if (str1[i] == str2[i]) {
            continue;
        }
        else {
            result = str1[i] > str2[i] ? 1 : -1;
            break;
        }
    }
    return 0;
}

//Method 2: pointer operation:   
int my_strcmp1(const char* str1, const char* str2) {
    assert(str1 != NULL && str2 != NULL);
    int i = 0;
    while (*str1 == *str2) { //abc       abc
        if (*str1 == '\0' && *str2 == '\0') {
            return 0;
        }
        str1++;
        str2++;
    }
    return *str1 > *str2 ? 1 : -1;
}

int main()
{
    const char* str1 = "abc";
    const char* str2 = "abg";
    int num = my_strcmp1(str1,str2);
    printf("%d",num);
    return 0;
}

(3)tstrcat(p, p1) additional string (connection string)

char* my_strcat(char* str1, const char* str2) {
    assert(str1!=NULL && str2!=NULL);
    int len = strlen(str1);
    // Connect str2 data to str1
    int i = 0;
    for (;i < strlen(str2); i++) {
        str1[len+i] = str2[i];
    }
    str1[len+i] = '\0'; // String end tag '\ 0'
    return str1;
}

int main()
{
    char ch[10] = "abc";//'\0'
    char *res = my_strcat(ch, "def"); //abcdef
    strcat(char*str1,const char*str2)
    printf("%s",res);
    return 0;
}

(4) strcpy(p, p1) copies the string  

char* my_strcpy(char* str1, const char* str2) {
    assert(str1 != NULL && str2 != NULL);
    //Pointer implementation method:
    while (*str2!='\0') { //abc\0     abc
        *str1 = *str2;
        str1++;
        str2++;
    }
    *str1 = '\0';
    return str1;  

int main()
{
   char str1[10] = "abc";
   const char* str2 = "defghi";
   char* res = my_strcpy(str1, str2);
   printf("%s",res);

Tags: C

Posted on Wed, 01 Dec 2021 11:49:54 -0500 by john010117