Embedded engineer interview questions set - C language

Table of contents

Precompiled

1. What is precompilation and when is precompilation required

2. The process of generating machine code from a high-level language source program

3. What is the difference between #include and #include "file.h"?

4. What is the role of ifndef/define/endif in the header file?

5. How to judge whether a program is compiled by C compiler or C++ compiler?

6. What is the purpose of the preprocessor flag #error?

macro definition

1. Declare a constant with the preprocessing directive #define to indicate how many seconds there are in a year (ignoring the leap year issue).

2. A "standard" macro that swaps two parameter values.

3. Write a "standard" macro MIN that takes two arguments and returns the smaller one.

4. Given an array table, use a macro definition to find the number of elements in the data

5. Embedded systems always require the user to perform bit operations on variables or registers. Given an integer variable a, write two pieces of code, the first one sets the bit3 of a, and the second one clears the bit3 of a. In the above two operations, keep the other bits unchanged.

6. Advantages and disadvantages of macros and functions with parameters

7.Typedef function:

8. Typedef, #define define data types, what is the difference between the two? Which one is better?

Selection and Loop Structures

1. Infinite loops are often used in embedded systems. How do you write infinite loops in C?

2. What is the difference between do...while and while...?

3. Cannot be the parameter type of switch()

pointers and arrays

1. Give the following definition with the variable a

2. A pointer to a string constant, a constant pointer to a string (const)

3. What is a wild pointer, its causes, and how to avoid it

4. Briefly describe the difference between arrays and pointers?

5. Write out the comparison statements between variable a of BOOL, int, float and pointer type and "zero".

6. void type pointer

7. What is the difference between "reference" and pointer?

8. The output of the following code is: A

static

1. What is the function of the keyword static?

2. What is the difference between static local variables and ordinary local variables?

3. What is the difference between static global variables and ordinary global variables?

4. What is the difference between a static function and an ordinary function?

const

1. What does the keyword const mean?

2. What do the following const declarations mean?

3. Please tell me what are the advantages of const compared with #define?

4. Use const reason

volatile

1. What does the keyword volatile mean and give three different examples.

2. Can a parameter be both const and volatile? explain why.

3. Can a pointer be volatile? explain why.

4. What is wrong with the following function:

5. const, volatile meaning

6. The role of const, volatile and the stage of action

7. const, volatile modify a variable at the same time

operation

1. What is the output of the code below and why?

2. The C language allows some shocking constructs, is the following construct legal, and if so what does it do? **

3. Please write the output of the following code

4. Write the output of the following code

5. Please find all the errors in the following code

6. What is wrong with the following program?

7. What will happen in the following program?

variable scope

Memory

1. Program memory allocation

 2. Access to a fixed memory location. The value of the integer variable whose absolute address is 0x67a9 is 0xaa66. The compiler is a pure ANSI compiler, writing code to accomplish this task.

3. What is the difference between a queue and a stack?

4. Explain the difference between heap and stack

5. What is the general cause of stack overflow?

Common standard library functions

1. The difference between sizeof and strlen

2. Is there a problem with the two sizeof usages in the following code?

3. There is a structure as follows:

common algorithm

1. What is the time complexity of the bubble sort algorithm?

2. Perform a binary search on an ordered array containing 20 elements, and the starting subscript of the array is 1, then find the subscript of the comparison sequence of A[2] as (B)

3. When the linear table (a1, a2,...,an) is stored in a linked manner, the time complexity of accessing the i-th element is (C)

4. On a 10-order B-tree, the maximum number of keywords contained in each tree root node is allowed to be ( ), and the minimum number of keywords allowed is (B).


Precompiled

1. What is precompilation and when is precompilation required

A: Precompilation, also known as preprocessing, is to do some code text replacement work. The instructions at the beginning of #, such as copying the file code contained in #include, #define macro definition replacement, conditional compilation, etc., are the preparatory work for compilation.
The preprocessing functions provided by C mainly include the following three types:
1) Macro definition. #define
2) file includes. #include. This directive instructs the compiler to insert the entire contents of the xxx.xxx file here.
3) Conditional compilation. #ifdef/#ifndef, #endif, #if/#else

When to precompile:
1) Always use large code bodies that don't change often.
2) A program consists of multiple modules, all using a standard set of include files and the same compilation options.

2. The process of generating machine code from a high-level language source program

Preprocessing --> Compilation --> Assembly --> Link

Preprocessing: Insert all the files specified by the #include command and the macros specified by the #define statement into the high-level language source program.

Compile: Compile the preprocessed source program file to generate the corresponding assembly language program.

Assembly: An assembler converts an assembly language source program file into a relocatable machine language object code file.

Linking: The linker links multiple relocatable machine language object files and library routines (such as printf() library function) to generate the final executable object file (machine code).

3. What is the difference between #include <file.h> and #include “file.h”?

Answer: The former looks for file.h from the standard library path;
the latter looks for file.h from the current working path.

4. What is the role of ifndef/define/endif in the header file?

Answer: Prevent the header file from being repeatedly referenced.

5. How to judge whether a program is compiled by C compiler or C++ compiler?

answer:

#ifdef __cplusplus
    printf(“c++”);
#else
    printf(“c”);
#endif

6. What is the purpose of the preprocessor flag #error?

Answer: As long as you encounter #error, a compilation error will pop up. The purpose is to ensure that the program is compiled as you imagined.

macro definition

1. Declare a constant with the preprocessing directive #define to indicate how many seconds there are in a year (ignoring the leap year issue).

答:#define SECONDS_PER_YEAR    (60 * 60 * 24 * 365)UL

2. A "standard" macro that swaps two parameter values.

答:#define SWAP(a,b)    (a)=(a)+(b); (b)=(a)-(b); (a)=(a)-(b)

3. Write a "standard" macro MIN that takes two arguments and returns the smaller one.

答:#define MIN(A, B)    ((A)>=(B)) ? (B) : (A)

4. Given an array table, use a macro definition to find the number of elements in the data

答:#define NTBL(tab)    (sizeof(tab) / sizeof(tab[0]))

5. Embedded systems always require the user to perform bit operations on variables or registers. Given an integer variable a, write two pieces of code, the first one sets the bit3 of a, and the second one clears the bit3 of a. In the above two operations, keep the other bits unchanged.

answer:

    #define BITS_CLR(v, n)      v &= ~(1u<<n)
    #define BITS_SET(v, n)      v |= (1u<<n)
 
    static int a;
 
    BTIS_SET(a, 3);
    BTIS_CLR(a, 3);

6. Advantages and disadvantages of macros and functions with parameters

answer:

With parameter macro advantage

1) There are no type conversion and operation problems for parameters, because macros with parameters are just replacements;

2) Takes no runtime (no memory, context saving, passing by value, returning, etc.)

shortcoming

1) The number of times the macro is used is large, and the program increases a lot;

2) accounted for compilation time

function with parameters advantage

1) The number of function calls is large, and the program increases little;

2) Does not account for compilation time

shortcoming

1) There are type conversion and operation problems in parameters;

2) Calling takes up running time (allocation of memory, context protection, value transfer, return)

7.Typedef function:

Answer: Aliasing data types

8. Typedef, #define define data types, what is the difference between the two? Which one is better?

Answer: typedef is better than #define, especially when there are pointers. Please see the example:

typedef char* pStr1;
#define pStr2 char*
pStr1 s1, s2;
pStr2 s3, s4;

In the above variable definitions, s1, s2, and s3 are all defined as char *, while s4 is defined as char, which is not the pointer variable we expected. The fundamental reason is that #define is just a simple string replacement and typedef is is to give a new name to a type. In the above example, the define statement must be written as pStr2 s3, *s4; so that it can be executed normally.

Selection and Loop Structures

1. Infinite loops are often used in embedded systems. How do you write infinite loops in C?

answer:

while(1) //方案1
{
    ;
}
for( ;1 ;) //方案2
{
    ;
}
Loop:
goto Loop; //方案3

2. What is the difference between do...while and while...?

Answer: The previous cycle will be judged again, and the latter judgment will be cycled later.

3. Cannot be the parameter type of switch()

Answer: real

pointers and arrays

1. Give the following definition with the variable a

a) An integer (Aninteger)?
b) A pointer to an integer (Apointer to an integer)?
c) A pointer to a pointer, which points to an integer (A pointer to an integer) pointer to an integer)?
d) An array of 10 integers?
e) An array of 10 pointers pointing to an integer (An array of 10 pointers to integers)?
f) A pointer to an array of 10 integers?
g) A pointer to a function that takes an integer parameter and returns an integer ( A pointer to a function that takes an integer as an argument and returns an integer)?
h) An array of 10 pointers to a function that takes an integer parameter and returns an integer ( An array of ten pointers to functions that take an integer argument and return an integer )
Answer:

a) int a;
b) int *a;
c) int **a;
d) int a[10];
e) int *a[10];
f) int (*a)[10];
g) int (*a)(int );
h) int (*a[10])(int );

2. A pointer to a string constant, a constant pointer to a string (const)

answer:

const char* p = "hello"; //指向 "字符串常量"
p[0] = 'X'; //错误! 想要修改字符串的第一个字符. 但是常量不允许修改
p = p2; //正确! 让p指向另外一个指针.
char* const p = "hello"; //指向字符串的" 常量的指针"
p[0] = 'X'; //正确! 允许修改字符串, 因为该字符串不是常量
p = p2; //错误! 指针是常量, 不许修改p的指向

char const * and const char* are the same. The position of const is the same on the left or right of char. The
const of the constant pointer should be written on the right of the * asterisk.
The writing method of the constant pointer pointing to the constant string is const char* const p = "xx"; need 2 const

3. What is a wild pointer, its causes, and how to avoid it

Answer: The wild pointer means that the location pointed by the pointer is unknown.
Reasons:
1. The pointer variable is not initialized
2. The pointer is not emptied after release (the variable pointed to by the pointer is destroyed before the pointer)
3. The pointer operation exceeds the variable scope
Avoidance:
1. Set NULL when initializing
2. Set NULL when releasing NULL

4. Briefly describe the difference between arrays and pointers?

Answer:
Arrays are created in static storage (such as global arrays), or on the stack.
A pointer can point to any type of memory block at any time.
(1) Differences in revised content

    char a[] = “hello”;
    a[0] = ‘X’;
    char *p = “world”; // 注意p 指向常量字符串
    p[0] = ‘X’; // 编译器不能发现该错误,运行时错误

(2) Use the operator sizeof to calculate the capacity (number of bytes) of the array. sizeof(p), p is a pointer to get the number of bytes of a pointer variable, not the memory capacity pointed to by p. The C++/C language has no way to know the memory capacity pointed to by the pointer, unless it is remembered when applying for memory. Note that when an array is passed as an argument to a function, the array automatically degenerates into a pointer of the same type.

    char a[] = “hello world”;
    char *p = a;
    printf("%d\r\n", sizeof(a)); // 12 字节
    printf("%d\r\n", sizeof(p)); // 4 字节

Calculate the memory capacity of arrays and pointers

    void Func(char a[100])
    {
        printf("%d\r\n", sizeof(a));; // 4 字节而不是100 字节
    }

5. Write out the comparison statements between variable a of BOOL, int, float and pointer type and "zero".

answer:

BOOL :      if( !a ) or if( a )
int :       if(a == 0)
float :     const float EXP = 0.000001; 
            if((a >= -EXP) && (a <= EXP))
pointer :   if(a != NULL) or if(a == NULL)

6. void type pointer

The pointer has two attributes: the address and length of the variable/object, but the pointer only stores the address, and the length depends on the type of the pointer; the compiler addresses backward from the address pointed to by the pointer according to the type of the pointer, and the pointer type is different. The address range is also different.
For example:

int  从指定地址向后寻找4字节作为变量的存储单元
double  从指定地址向后寻找8字节作为变量的存储单元
void  即“无类型”,void *则为“无类型指针”,可以指向任何数据类型。
void指针  可以指向任意类型的数据,即可用任意数据类型的指针对void指针赋值。

For example:

    int *pint;
    void *pvoid; //它没有类型,或者说这个类型不能判断出指向对象的长度
    pvoid = pint; //只获得变量/对象地址而不获得大小,但是不能 pint = pvoid;

If you want to assign pvoid to other types of pointers, you need to cast. like:

    pint = (int *)pvoid; //转换类型也就是获得指向变量/对象大小

The void pointer cannot be re-referenced (that is, the meaning of fetching the content)
because the void pointer only knows the starting address of the variable/object, but does not know the size of the variable/object (accounting for a few bytes), so the content cannot be fetched correctly. In actual programming, in order to meet the ANSI standard and improve the portability of the program, we can write the code to achieve the same function as follows:

    void*pvoid;
    (char*)pvoid++; //ANSI:正确;GNU:正确
    (char*)pvoid+=1; //ANSI:错误;GNU:正确

7. What is the difference between "reference" and pointer?

answer:

引用必须被初始化,指针不必。
引用初始化以后不能被改变,指针可以改变所指的对象。
不存在指向空值的引用,但是存在指向空值的指针。
指针是地址,指针变量是存放地址的变量,是对目标变量的间接操作。
引用实质就是目标变量的别名,对引用的操作就是对目标变量的操作。

8. The output of the following code is: A

#include
void change(int * a, int &b, int c)
{
    c = *a;
    b = 30; //引用
    *a = 20;
}
 
int main ( )
{
    int a=10, b=20, c=30;
    change(&a,b,c);
    printf(“%d,%d,%d,”,a,b,c);
    return 0;
}

 A 20, 30, 30
B 10, 20, 30
C 20, 30, 10
D 10, 30, 30

static

1. What is the function of the keyword static?

Answer:
1) In the function, the modified variable is a static local variable, which is only initialized once, and its last value is maintained during the function call.
2) In the file, the modified variable is a local static global variable, which is only initialized once, and is only used in this file, and cannot be used in other files.
3) In the file, the modified function is a local static function, which is only used in this file and not available in other files.

2. What is the difference between static local variables and ordinary local variables?

Answer:
1) Static local variables have the same scope as ordinary local variables, both within functions, but with different storage types.
2) The static local variable is a static storage method, and the lifetime is always there;
3) The ordinary local variable is a non-static storage method, and the lifetime is the current function call, and the function is released when the function returns.

3. What is the difference between static global variables and ordinary global variables?

Answer:
1) Static global variables and ordinary global variables are both static storage methods, but their scopes are different.
2) The scope of static global variables can only be used in one source file;
3) The scope of ordinary global variables can be used in multiple source files.

4. What is the difference between a static function and an ordinary function?

Answer: The scope of a static function is different from that of a normal function. static functions are only used within this file. Ordinary functions can be used in multiple files.

Summary:
static changes the lifetime of local variables;
static changes the scope of global variables;
static changes the scope of functions;

const

1. What does the keyword const mean?

const means read-only, immutable.
Functions: Define constants, modify function parameters, and modify function return values.
Definition: The data type modified by const refers to the constant type, and the value of the variable or object of the constant type cannot be updated.
Purpose: The initial purpose of const is to replace precompiled instructions, eliminate its shortcomings, and inherit its advantages.

2. What do the following const declarations mean?

const int a; //a是一个 常整型数
int const a; //a是一个 常整型数
const int *a; //a是一个指向 常整型数 的指针(整型数是不可修改,但指针可以)
int * const a; //a是一个指向整型数的 常指针(指针指向的整型数是可以修改的,但指针是不可修改的
const int * const a; //a是一个指向 常整型数的 常指针(指针指向的整型数 和 指针 都不可修改)

3. Please tell me what are the advantages of const compared with #define?

Answer: Things modified by const are subject to compulsory protection, which can prevent accidental changes and improve the robustness of the program.
1) const constants have data types, but macro constants do not have data types. The compiler can perform type safety checks on the former. For the latter, only character replacement is performed, without type safety checks, and unexpected errors may occur during character replacement.
2) Some integrated debugging tools can debug const constants, but cannot debug macro constants.

4. Use const reason

(1) Define const constants, which are immutable.
         For example: const int Max=100; int Array[Max];
(2) It can avoid the appearance of ambiguous numbers, and it is also very convenient to adjust and modify parameters.
         As in (1), if you want to modify the content of Max, you only need to: const int Max=you want; that's it!
(3) It is convenient for type checking, so that the compiler has a better understanding of the processing content and eliminates some hidden dangers.
         For example: void f(const int i) { .........} The compiler will know that i is a constant and is not allowed to be modified; (
4) It can protect the modified things to prevent accidental modification and enhance The robustness of the program.
         For example (2), if i is modified in the function body, the compiler will report an error;
(5) it can save space and avoid unnecessary memory allocation.
         For example:

    #define PI      3.14159 //常量宏
    const double PI = 3.14159; //此时并未将Pi放入RAM中 ......
    double a=PI; //此时为Pi分配内存,以后不再分配!
    double b=PI; //编译期间进行宏替换,分配内存
    double c=Pi; //没有内存分配
    double d=PI; //再进行宏替换,又一次分配内存!
const 定义常量从汇编的角度来看,只是给出了对应的内存地址;
#define 给出的是立即数;
所以,const 定义的常量在程序运行过程中只有一份拷贝,
而 #define 定义的常量在内存中有若干个拷贝。

(6) Improved efficiency.
The compiler usually does not allocate storage space for ordinary const constants, but saves them in the symbol table, which makes it a constant during compilation, without the operation of storing and reading memory, making it highly efficient.

volatile

1. What does the keyword volatile mean and give three different examples.

Answer: volatile means easy to change, and the compiler will not optimize the variable that defines volatile. To be precise, the optimizer must carefully re-read the value of this variable every time it uses it, instead of using a backup stored in a register.
The following are a few examples of volatile variables:
1) Hardware registers of parallel devices (such as: status registers)
2) Non-automatic variables that will be accessed in an interrupt service subroutine (Non-automatic variables)
3) Used in multi-threaded applications
The volatile keyword is a type modifier for variables shared by several tasks .
Role: Prevent the compiler from optimizing the code.
Where to use:
1) Variables modified in the interrupt service program for detection by other programs need to add volatile;
2) Flags shared between tasks in a multi-tasking environment should add volatile;
3) Memory-mapped hardware registers usually also need to add volatile instructions , because each reading and writing to it may have different meanings;
       in addition, the above situations often have to consider the integrity of the data at the same time (several interrelated signs are interrupted and rewritten after half of the reading), in 1 can be achieved by turning off interrupts, 2 can disable task scheduling, and 3 can only rely on good hardware design.

2. Can a parameter be both const and volatile? explain why.

Answer: Yes. An example is a read-only status register. It is volatile because it can be changed unexpectedly. It is const because programs should not attempt to modify it.

3. Can a pointer be volatile? explain why.

Answer: Yes. Although this is not very common. An example is when a service subroutine modifies a pointer to a buffer.

4. What is wrong with the following function:

int square(volatile int *ptr)
{
    return *ptr * *ptr;
}

Answer: There is a trick in this code. The purpose of this code is to return the square of the value pointed to by the pointer ptr. However, since ptr points to a volatile parameter, the compiler will generate code similar to the following:

int square(volatile int *ptr)
{
    int a,b;
    a = *ptr;
    b = *ptr;
    return a * b;
}

Since the value of *ptr may be changed unexpectedly, a and b may be different. As a result, this code may not return the square value you expect!
The correct code is as follows:

long square(volatile int *ptr)
{
    int a;
    a = *ptr;
    return a * a;
}

5. const, volatile meaning

(1) The meaning of const is "please use it as a constant", not "don't worry, it must be a constant".
(2) The meaning of volatile is "please don't do self-righteous optimization, this value may change", not "you can modify this value".

6. The role of const, volatile and the stage of action

(1) const is only useful at compile time, and useless at run time.
const is guaranteed to be in the "source code" of C at compile time, and there is no place to modify the variables it modifies (if there is, an error will be reported and the compilation will fail), while Whether the value of the variable is changed during runtime is not restricted by const.
(2) volatile is useful both at compile time and at run time.
Tell the compiler at compile time: please don’t do self-righteous optimization, the value of this variable may change;
at run time: every time you use the value of this variable, change it from Get the value of the variable in memory.

补充:
编译期 -- C编译器将源代码转化为汇编,再转化为机器码的过程;
运行期 -- 机器码在CPU中执行的过程。

7. const, volatile modify a variable at the same time

Answer:
(1) "The compiler generally does not allocate memory for const variables, but saves it in the symbol table, which makes it a value during compilation, without the operation of storing and reading memory." (2)
volatile The function is to "tell the compiler that something that may change at any time must be re-taken from memory every time it is used".

operation

1. What is the output of the code below and why?

void foo(void)
{
    unsigned int a = 6;
    int b = -20;
    (a+b > 6)? printf("> 6") : printf("<= 6");
}

Answer: ">6". Reason: When there are signed and unsigned types
in the expression , all operands are automatically converted to unsigned types . So -20 becomes a very large positive integer, so the expression evaluates to greater than 6.

2. The C language allows some shocking constructs, is the following construct legal, and if so what does it do? **

int a = 5, b = 7, c;
c = a+++b;

Answer: Legal, but badly regulated. After running this code, a = 6, b = 7, c = 12.

3. Please write the output of the following code

#include
main()
{
    int a,b,c,d;
    a=10;
    b=a++;
    c=++a;
    d=10*a++;
    printf(“b,c,d:%d,%d,%d”,b,c,d);
    return 0;
}

Answer: 10, 12, 120

4. Write the output of the following code

#include
int inc(int a)
{
    return(++a);
}
    
int multi(int *a, int *b, int *c)
{
    return(*c = *a * *b);
}
 
typedef int(FUNC1)(int in);
typedef int(FUNC2) (int*,int*,int*);
void show(FUNC2 fun,int arg1, int*arg2)
{
    FUNC1 p = &inc;
    int temp = p(arg1);
    fun(&temp, &arg1, arg2);
    printf(“%d\n”, *arg2);
}
 
main()
{
    int a;
    show(multi, 10, &a);
    return 0;
}

Answer: 110

5. Please find all the errors in the following code

Description: The following code reverses a string, such as "abcd" becomes "dcba" after reverse

#include”string.h”
main()
{
    char* src = ”hello,world”;
    int len = strlen(src);
    char* dest = (char*)malloc(len);
    char* d = dest;
    char* s = src[len];
    while(len–- != 0) d++ = s–-;
    printf(“%s”,dest);
    return 0;
}

Answer: Method 1:

int main()
{
    char* src = “hello,world”;
    int len = strlen(src);
    char* dest = (char*)malloc(len+1); //要为\0分配一个空间
    char* d = dest;
    char* s = &src[len-1];//指向最后一个字符
    while(len–- != 0) *d++ = *s–-;
    *d = 0; //尾部要加\0
    printf(“%s\n”,dest);
    free(dest); //使用完,应当释放空间,以免造成内存汇泄露
    return 0;
}

Method 2:

#include<string.h>
#include<stdio.h>
 
int main(void)
{
    char str[]="hello,world";
    int len=strlen(str);
    char t;
    for(int i=0; i <= (len/2); i++)
    {
        t=str[i];
        str[i]=str[len-i-1]; 
        str[len-i-1]=t;
    }
    printf("%s",str);
    return 0;
}

6. What is wrong with the following program?

int a[60][250][1000], i, j, k;
for(k=0; k<=1000; k++)
for(j=0; j<250; j++)
for(i=0; i<60; i++)
a[i][j][k]=0;

Answer: Change the inside and outside of the loop statement

7. What will happen in the following program?

#define Max_CB 500
 
void LmiQueryCSmd(Struct MSgCB * pmsg)
{
    unsigned char ucCmdNum;
    ......
    for(ucCmdNum=0; ucCmdNum<Max_CB; ucCmdNum++)
    {
        ......;
    }
}

Answer: infinite loop

variable scope

1. Is there any difference between global variables and local variables in memory? If yes, what is the difference?
Answer:
1) Global variables are stored in the static data area, and local variables are stored in the stack.
2) The scope of a global variable is the entire function, and the scope of a local variable is the function in which the variable is declared

2. Can local variables have the same name as global variables?
Answer: Yes, the local will block the global. To use global variables, you need to use "::"

3. Can global variables be defined in a header file that can be included by multiple .C files? Why?
Answer: Yes, declare global variables with the same name in static form in different C files. There can only be an initial value assigned to this variable in one C file, and the connection will not go wrong at this time.

4. How to refer to an already defined global variable?
Answer: Use the extern keyword to declare global variables in the header file.

Memory

1. Program memory allocation

Answer:
1) Stack area (stack) - automatically allocated and released by the compiler, storing function parameter values, local variables, etc.
2) Heap area (heap) - generally allocated and released by the programmer. Allocation uses new and malloc, and release uses deleted and free
3) Global area (static area) (static) ---- global variables and static variables are stored together. The initialized ones are stored in one area, and the uninitialized ones are stored in another area (BSS).
4) Constant area - store constant character strings.
5) Program code area - store the binary code of the function body.
Example program:

int a=0; //全局初始化区
char *p1; //全局未初始化区
main()
{
    int b; //栈
    char s[]=”abc”; //栈
    char *p2; //栈
    char *p3=”123456″; //123456\\0在常量区,p3在栈上。
    static int c=0; //全局(静态)初始化区
    p1 = (char*)malloc(10);
    p2 = (char*)malloc(20); //分配得来得10和20字节的区域就在堆区。
    strcpy(p1,”123456″); //123456\\0放在常量区,编译器可能会将它与p3所向”123456″优化成一个地方。
}

 

 2. Access to a fixed memory location. The value of the integer variable whose absolute address is 0x67a9 is 0xaa66. The compiler is a pure ANSI compiler, writing code to accomplish this task.

int *ptr;
ptr = (int *)0x67a9;
*ptr = 0xaa55;
 
一个较晦涩的方法是:
*(int * const)(0x67a9) = 0xaa55;
 
即使你的品味更接近第二种方案,但我建议你在面试时使用第一种方案。

3. What is the difference between a queue and a stack?

Answer: Queue first in first out, stack last in first out

4. Explain the difference between heap and stack

Answer:
1) How to apply.
stack: automatically allocated by the system.
For example: declare a local variable int b in the function; the system automatically creates space for b in the stack

heap:需要程序员自己申请,并指明大小。在c中malloc函数
如:p1 = (char*)malloc(10); //在C++中用new运算符。注意p1本身是在栈中的。 `

2) Comparison of application efficiency.
Stack: Automatically allocated by the system, the speed is faster. But the programmer is out of control.
Heap: The memory allocated by malloc/new is generally slow and prone to memory fragmentation, but it is the most convenient to use.
3) There is a limit on the size of the application.
Stack: The system is predetermined. It is configured in advance. The stack gets less space.
Heap: The space obtained by programmers defining the heap is more flexible and larger.
4). Storage content in the heap and stack.
Stack: store function local temporary variables, field protection, etc.
Heap: The specific content in the heap is arranged by the programmer.

5. What is the general cause of stack overflow?

Answer:
1. Garbage resources are not recycled;
2. Recursive calls with too deep layers

Common standard library functions

1. The difference between sizeof and strlen

char str[20]="0123456789";
int a=strlen(str); //a=10; strlen计算字符串的长度,以'\0'为字符串结束标记(长度不包含'\0')。
int b=sizeof(str); //b=20; sizeof计算数组str[20] 所占的内存空间的大小,不受里面存储的内容影响。
char* ss = "0123456789";

sizeof(ss) result 4 ——> ss is a character pointer pointing to a string constant, and sizeof obtains the space occupied by a pointer.
sizeof(*ss) result 1 ——> *ss is the memory space occupied by the first character '0', which is char type, occupying 1 digit
strlen(ss) result 10 ——> If you want to get this string length, you must use the strlen
sizeof structure as the total space of the data type defined in the structure (note the byte alignment).
sizeof is the size of the largest data type of the data type defined in union for union.

2. Is there a problem with the two sizeof usages in the following code?

void UpperCase( char str[] ) //将 str 中的小写字母转换成大写字母
{
    for(int i=0; i<sizeof(str); i++)
    {
        if( 'a'<=str[i] && str[i]<='z' )
        str[i] -= ('a'-'A' );
    }
}
 
char str[] = "aBcDe";
printf("str字符长度为:" sizeof(str) / sizeof(str[0]));
UpperCase( str );
printf("%s", str );

answer:

1) There is a problem with sizeof in the function. According to the grammar, if sizeof is used for arrays, it can only measure the size of static arrays, and cannot detect the size of dynamically allocated or external arrays.

2) The str outside the function is a statically defined array, so its size is 6. The str inside the function is actually just a pointer to a string without any additional information related to the array, so sizeof only applies to the above When looking at pointers, a pointer is 4 bytes, so 4 is returned.

3. There is a structure as follows:

struct A
{
    long a1;
    short a2;
    int a3;
    int *a4;
};

What is the size calculated by sizeof(struct A) under the 64-bit compiler? A
A 24
B 28
C 16
D 18

common algorithm

1. What is the time complexity of the bubble sort algorithm?

Answer: O(n^2)

/**
  ******************************************************************************
  * @brief   冒泡排序加强版 函数
  * @param   *ary    数据指针
  * @param   len     数据长度
  * @param   dir     排序方向(1--降序;0--升序) 
  * @return  None
  * @note    升降排列通用 
  ******************************************************************************
  */
#define BubbleType     int //元素类型
void BubbleSortPlus(BubbleType *ary, unsigned char len, unsigned char dir)
{
    BubbleType tmp;
    unsigned char i, j;
 
    len--; //自减1。注意不能少 
    for(i=0; i<len; i++) //外循环为排序趟数,len个数进行len-1趟
    {
        for(j=0; j<len-i; j++) //内循环为每趟比较的次数,第i趟比较len-i次
        {
            if((ary[j] < ary[j+1]) ^ dir) //相邻元素比较,若逆序则交换(升序为左大于右,降序反之)
            {
                tmp = ary[j];
                ary[j] = ary[j+1];
                ary[j+1] = tmp;
            }
        }
    }
}

2. Perform a binary search on an ordered array containing 20 elements, and the starting subscript of the array is 1, then find the subscript of the comparison sequence of A[2] as (B)

A 9,5,4,2
B 10,5,3,2
C 9,6,2
D 20,10,5,3,2

int BinSearch(const int *Array, int low, int high, int target)
{
    int mid;
    while(low <= high)
    {
        mid = low + (high - low) / 2;
        if(target == Array[mid])  return mid;
        else if(target < Array[mid]) high = mid - 1;
        else if(target > Array[mid]) low  = mid + 1;      
    }
    return -1;
}

3. When the linear table (a1, a2,...,an) is stored in a linked manner, the time complexity of accessing the i-th element is (C)

A O(i)
B O(1)
C O(n)
D O(i-1)

4. On a 10-order B-tree, the maximum number of keywords contained in each tree root node is allowed to be ( ), and the minimum number of keywords allowed is (B).

A 10,5
B 9,4
C 8,3
D 7,6

Reprinted article notes

————————————————
Copyright statement: This article is the original article of CSDN blogger "Jiangzai Jianghu", following the CC 4.0 BY-SA copyright agreement, please attach the original source link and this statement.
Original link: https://blog.csdn.net/weixin_46672094/article/details/125445400

Guess you like

Origin blog.csdn.net/qq_50635297/article/details/130781422