Basic knowledge of embedded C language -- compound type & Memory & etc

catalogue

1. Generate random number

2. Value transmission and address transmission

3. Return the address of the variable:

4. Address to return to the heap area:

5. Structure array

6. Structure pointer

7. Structure sleeve pointer

8. Structure array as formal parameter of function

9. Enumeration:

10. Memory storage mode: size side

 11. Exercises

12. Function of typedef

13. sizeof

14. Memory partition

(1) Before running the program

(2) After the program runs

 15. Growth direction of stack

 

1. Generate random number

srand(): used before calling the rand() function. It is a function that sets the seed of random numbers.

rand(): a function that generates random numbers.

time(): time(NULL) the return value of this function is used as the parameter of the srand() function. It means that the current system time is used as the seed of random number to generate random number. The parameter is NULL, which is used to obtain the system time.

int main()
{
    unsigned long n;
    srand((unsigned)time(NULL));
    for (int i = 0; i < 10; i++)
    {
        //n = rand() % 26 + 'a';
        n = rand();
        printf("%d\n", n);
    }

    return 0;
}

2. Value transmission and address transmission

The value of an argument cannot be changed by passing the value of a function. However, if you pass the address of the argument, you can change the value of the argument when calling the function.

3. Return the address of the variable:

Only the address of the ordinary local variable cannot be returned, because the ordinary local variable is released after the end of the function.

eg:

int a = 10;
int* fun()
{
    static int a =10;
    a *= 10;
    return &a;
}

int main()
{
    int *p = fun();
    *p = 2000;            // If the space pointed to by p is not released (static local variable), you can operate on this address
    printf("%d\n", *p);

    return 0;
}

4. Address to return to the heap area:

The heap address can be returned as long as it is not released.

5. Structure array

Is an array, and each element of the array is a structure.

struct stu
{
    int id;
    int age;
    char name[24];
};

int main()
{
    struct stu num[3] = { {1,10,"paul"},{2,20,"rose"},{3,30,"kobe"}};
    for (int i = 0; i < sizeof(num) / sizeof(num[0]); i++)
    {
        printf("%d %d %s\n", num[i].id, num[i].age, num[i].name);
    }

    return 0;
}

6. Structure pointer

struct STUDENT
{
    int id;
    int age;
    char name[24];
};

int main()
{
    struct STUDENT stu;         //Define a structure variable stu
    struct STUDENT* p = NULL;   //Define a pointer variable p that points to the struct STUDENT structure type
    p = &stu;
    strcpy(p->name, "wo");
    p->id = 1;
    p->age = 18;
    printf("%d %d %s ", p->id, p->age, p->name);

    return 0;
}

7. Structure sleeve pointer

First, let's look at a pointer:

(1) For p = "hello", it means that the address of the string Hello is assigned to the pointer variable p, which is OK;

(2) For strcpy(q, "world"); You must first apply for a space for the pointer variable Q , and assign the space address applied by malloc to Q, and then execute the copy action. Otherwise, q is a wild pointer.

int main()
{
    char* p;
    p = "hello";

    char* q;
    q = (char*)malloc(128);
    strcpy(q, "world");

    return 0;
}

Look at the following:

struct t
{
    int a;
    char b;
};

struct tea
{
    int id;
    char* p;
    struct t* q;
};

int main()
{
    // tmp itself has space when it is defined, but the pointing space of tmp is only after malloc; p. q the same is true.
    struct tea* tmp = (struct tea*)malloc(sizeof(struct tea));   //Define the structure pointer variable tmp and make space for it
    tmp->id = 1; 
    tmp->p = (char*)malloc(100);                     // p is a wild pointer, which can only be assigned after opening up space
    strcpy(tmp->p, "hello");

    tmp->q = (struct t*)malloc(sizeof(struct t));   // q is a wild pointer, which can only be assigned after opening up space
    tmp->q->a = 100;

    free(tmp->p);
    free(tmp->q);
    free(tmp);        //malloc will be released several times after several times; Release from the inside out

    return 0;
}

8. Structure array as formal parameter of function

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <stdlib.h>
#include<string.h>

struct tea
{
    int id;
    char name[128];
};

void set_num(struct tea* p, int n)
{
    for (int i = 0; i < n; i++)
    {
        p[i].id = i + 10;
        char buf[128] = "";
        sprintf(buf, "%d%d%d", i, i, i);
        strcpy(p[i].name, buf);
    }
}

int main()
{
    struct tea num[5];
    memset(num, 0, sizeof(num));
    set_num(num, sizeof(num) / sizeof(num[0]));
    for (int i = 0; i < sizeof(num) / sizeof(num[0]); i++)
    {
        pritnf("%d %s\n", num[i].id, num[i].name);
    }

    return 0;
}

Output is:

10 000
11 111
12 222
13 333
14 444

9. Enumeration:

The values of constants listed in enumeration {} start from 0 by default.

10. Memory storage mode: size side

General household computers use small end storage. As explained by the following example,

int main()
{
	int a = 0x11223344;
	char* p = &a;

	printf("%x\n", *p);         //Low byte
	printf("%x\n", *(p + 1));
	printf("%x\n", *(p + 2));
	printf("%x\n", *(p + 3));   //High byte
 
	system("pause");
	return 0;
}

Output is:

44
33
22
11

 11. Exercises

(1)

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <stdlib.h>
#include<string.h>

typedef struct student
{
    char name[50];
    unsigned int age;
    int score;
}student;

void print_stu(student* stu, int n)
{
    int i = 0;
    printf("name\tage\tscore\n");
    for (i = 0; i < n; i++)
    {
        printf("%s\t%d\t%d\n", stu[i].name, stu[i].age, stu[i].score);
    }
}

void sort_stu(student* stu, int n)
{
    int i = 0;
    int j = 0;
    student tmp;

    for (i = 0; i < n - 1; i++)
    {
        for (j = 0; j < n - 1 - i; j++)
        {
            if (stu[j].score < stu[j + 1].score)
            {
                tmp = stu[j];
                stu[j] = stu[j + 1];
                stu[j + 1] = tmp;
            }
            else if (stu[j].score == stu[j + 1].score)
            {
                if (stu[j].age > stu[j + 1].age)
                {
                    tmp = stu[j];
                    stu[j] = stu[j + 1];
                    stu[j + 1] = tmp;
                }
            }
        }
    }
}

int main()
{
    student stu[5] =
    {
        {"paul", 18, 90},
        {"rose", 19, 80},
        {"kobe", 19, 90},
        {"jack", 20, 60},
        {"pete", 19, 70}
    };
    int n = sizeof(stu) / sizeof(stu[0]);
    printf("Before sorting:\n");
    print_stu(stu, n);
    sort_stu(stu, n);

    printf("After sorting:\n");
    print_stu(stu, n);

    return 0;
}

(2)fflush(stdout); / / refresh the standard output buffer, print the contents of the output buffer to the standard output device, and connect them to printf to improve the printing efficiency

12. Function of typedef

(1) Simplify structure creation variables

struct MY_WORLD
{
	int x;
	char y;
};
typedef MY_WORLD myworld;
Equivalent to
typedef struct MY_WORLD
{
	int x;
	char y;
};

(2) Distinguish data types

char* x, y;
be x The data type is char*;y The data type is char. 

typedef char* pchar;
pchar a,b;
be a The data type is char*;b The data type is char*. 
Equivalent to: char *a, *b;

(3) Improve portability

13. sizeof

(1) sizeof() is not a function but an operator. It returns a value of type unsigned int.

(2) Count the memory space occupied by the array

Also note that when an array name is passed into a function, it is degenerated into a pointer that points to the address of the first element in the array. So the second printf output is 4, Cal_ Int arr [] in array (int arr []) is equivalent to int* arr.

void cal_Array(int arr[])
{
	printf("After passing to the function size of arr = %d\n",sizeof(arr));
}

int main()
{
	int arr[] = { 1,2,3,4.5 };
	printf("size of arr = %d\n",sizeof(arr));
	cal_Array(arr);

	system("pause");
	return 0;
}

Output is:

size of arr = 16
 After passing to the function size of arr = 4

14. Memory partition

(1) Before running the program

That is, before the program is loaded into memory, the executable program has been divided into three pieces of information, namely, code area (text), data area (data) and uninitialized data area (bss).

  • text: code area. Shared and read-only;
  • data: initialized global variables, static variables and constants;
  • bss: uninitialized global variables, static variables, constants; The data in this area is initialized to 0 or null (NULL) by the predecessor kernel at the beginning of program execution;

(2) After the program runs

Before the program is loaded into memory, the sizes of data area and bss area are fixed and cannot be changed during the program running.

Then, the executable program is run, and the operating system load s the physical hard disk program into memory. In addition to separating text, data and bss according to the information of the executable program, the stack area and heap area are added.

  • text: all executable codes are loaded into the code area, which cannot be modified during operation;
  • BSS and data: the BSS section and data section of the executable file are loaded respectively. The data life cycle of these two areas is the whole program running process.
  • Stack area: first in and last out; Store function parameter values, return values, local variables, etc.
  • Heap area: the capacity is much larger than the stack, which is used for dynamic memory allocation; It is located between the BSS area and the stack area in memory.

matters needing attention:

① The address of the local variable cannot be returned;

② Precautions for heap area: if memory is not allocated to the pointer in the calling function, the called function needs to allocate memory to the pointer summarized by the calling function using the advanced pointer.

As shown in the following two pictures, in the first picture, the pointer {p is not assigned, and the output is NULL; In the second picture, the pointer {p} is assigned the address of "helloworld".

 

 15. Growth direction of stack

Stack bottom: high address; Stack top: low address.

 

int main()
{
	int a = 10;    //Stack bottom, high address
	int b = 20;
	int c = 30;    //Stack top, low address

	printf("%d\n", &a);
	printf("%d\n", &b);
	printf("%d\n", &c);

	system("pause");
	return 0;
}

Output is:

17825456
17825444
17825432

Keywords: C C++

Added by BahBah on Fri, 31 Dec 2021 05:40:47 +0200