Picking up shells from the sea of questions No.10|C language written test small topic collection

1. bool, float, pointer variable and "zero value" comparison if statement.

Bool:

if(flag)

if(!flag)

//if(flagTRUE),if(flag1),if(flagFALSE),if(flag0), these are bad styles and do not score.

Float:

if((x>=-0.000001)&&(x<=0.000001))

//You cannot use floating-point variables with "", "!=" is compared with numbers, and should be converted into "<=", ">=", such as if(x0.0) if(x!=0.0), is wrong.

pointer:

if(p==NULL)

if(p!=NULL)

//if(p==0),if(p!=0),if§,if(!).bad style

2. Use the bottom line command mode of Vi compiler to realize string replacement

Replace all "xiaodai" in the current file with "banzhang".

():%s/xiaodai/banzhang/g

3. The output of the code below i++ is

int i = 1; 
int j = 2; 
int k = i+++j; 
cout << k << endl;
    /*3 i+++j是首先结合为i++(大多数的c编译系统都是尽可能多的将多个字符结合成为一个运算符,所以i+++j等价于(i++)+j),然后再+j;但是i++是事后计算,也就是先计算i+j然后再i++,所以k的值是1+2=3;然后i自增到2*/

4. The following code is a 32-bit program under Windows NT, please calculate the value of sizeof.

char str[]=”Hello”;
char *P = str;
int n=10;
//请计算 
sizeof(str) =;
sizeof(p) =;
sizeof(n) =; 
void func(char str[100]){
    
    
    sizeof(str) =;
    } 
void *p = malloc(100); 
sizeof(p) =;

Answer: 6 4 4 4 4, the array name can be considered as the first address of the first element of the array, but it is not a real address.

5. What is the use of ifndef/define/endif in the header file?

Prevent header files from being re-referenced.

6. Infinite loops are often used in embedded systems, how do you write infinite loops in C?

while(1){
    
    } 
for(;;){
    
    } 
loop:goto loop

7. Macro definition for exchanging two numbers

The macro that swaps the values ​​of two arguments is defined as

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

8. What is the output of the following code? Why

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

This question tests whether you understand the principles of integer auto-conversion in C, and I've found that some developers understand very little of these things. Anyway, the answer to the unsigned integer problem is that the output is ">6" . The reason is that all operands are automatically converted to unsigned types when there are signed and unsigned types in the expression . So -20 becomes a very large positive integer, so the expression evaluates to greater than 6 . This is very important for embedded systems where unsigned data types should be used frequently. If you get this question wrong, you're on the verge of not getting the job.

9. The difference between strlen and sizeof

Note: strlen calculates the length of the array without counting '\0'.

strlen( ) obtains the length of the string; sizeof( ) calculates the total memory space occupied by the string.

str[20] = {"abcd"};
strlen(str);	//结果为4
sizeof(str);	//结果为20

10.mystrcpy

char * strcpy( char *strDest, const char *strSrc ) //3
{
    
     
    assert( (strDest != NULL) && (strSrc != NULL) );//2 
    char *address = strDest; //1 
    while( (*strDest++ = * strSrc++) != '\0' );//3 
    return address; //1 
}
//strcpy能把strSrc的内容复制到strDest,为什么还要char * 类型的返回值?

In order to realize the chain expression.

11. Questions about dynamically applying for memory

void GetMemory(char *p) 
{
    
     
    p = (char *)malloc(100);
} 

void Test(void) 
{
    
     
    char *str = NULL; 
    GetMemory(str); 
    strcpy(str, "hello world"); 
    printf(str); 
} 
//请问运行Test函数会有什么样的结果?

The formal parameter passed in to the GetMemory( char *p ) function is a string pointer. Modifying the formal parameter inside the function cannot really change the value of the incoming formal parameter. After executing char *str = NULL; GetMemory( str ); str is still NULL;

To put it bluntly, the function GetMemory() does not return parameters.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-G1Krtu6u-1631525055073) (C:\Users\BMn94\AppData\Roaming\Typora\typora-user-images\ image-20210912173256457.png)]

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-LJ0oS09Z-1631525055075) (C:\Users\BMn94\AppData\Roaming\Typora\typora-user-images\ image-20210912173315679.png)]

12. What will be the result of running the Test function?

char *GetMemory(void) {
    
     
    char p[] = "hello world"; 
    return p; 
} 
void Test(void) {
    
     
    char *str = NULL; 
    str = GetMemory(); 
    printf(str); 
}

May be gibberish. char p[] = "hello world"; return p; The p[] array is a local automatic variable in the function, and the memory has been released after the function returns . This is a common mistake many programmers make, and its root lies in not understanding the lifetime of variables .

13. What will be the result of running the Test function?

void GetMemory(char **p, int num) 
{
    
     
    *p = (char *)malloc(num); 
} 
void Test(void) 
{
    
     
    char *str = NULL; 
    GetMemory(&str, 100); 
    strcpy(str, "hello"); 
    printf(str); 
}

It can output hello, and the memory of malloc is not released in the Test function . GetMemory avoids the above problems. The parameter passed into GetMemory is a pointer to a string pointer . However, after executing the memory application and assignment statement *p = (char *) malloc( num ); in GetMemory, it is not judged whether the memory application is successful. Above: if ( *p == NULL ) { ...//Process memory application failure processing}

void GetMemory(char **p, int num) 
{
    
     
    *p = (char *)malloc(num); 
    if ( *p == NULL ) {
    
     
        //进行申请内存失败处理 
    }
} 
void Test(void) 
{
    
     
    char *str = NULL; 
    GetMemory(&str, 100); 
    strcpy(str, "hello"); 
    printf(str); 
}

14. What will be the result of running the Test function?

wild pointer problem

void Test(void) 
{
    
     
    char *str = (char *) malloc(100); 
    strcpy(str, “hello”); 
    free(str); 
    if(str != NULL) 
    {
    
     
        strcpy(str, “world”); 
        printf(str); 
    } 
}

If the operation is successful, the output may be garbled characters . After char *str = (char *) malloc(100); it is not judged whether the memory application is successful; in addition, str is not set to empty after free(str) , which may become a For "wild" pointers , add: str = NULL;

void Test(void) 
{
    
     
    char *str = (char *) malloc(100); 
    strcpy(str, “hello”); 
    free(str); 
    if(str != NULL) 
    {
    
     
        str = NULL;
        strcpy(str, “world”); 
        printf(str); 
    } 
}

15. What does const mean?

const means "read-only" .

const int a; //a是一个常整型数; 

int const a; //a是一个常整型数; 

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

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

int const * a const; //a是一个指向常整型数的常指针(指针指向的整型数是不可修改的,同时指针也是不可修改的);
  1. The role of the keyword const is to convey very useful information to people who read your code. In fact, declaring a parameter as a constant is to tell the user the application purpose of this parameter. If you've ever spent a lot of time cleaning up other people's trash, you'll quickly learn to appreciate this extra bit of information. (Of course, programmers who know how to use const rarely leave garbage for others to clean up.)
  2. Using the keyword const may produce more compact code by giving the optimizer some additional information.
  3. Reasonable use of the keyword const can make the compiler naturally protect those parameters that do not want to be changed, preventing them from being modified by unintentional code. In short, this reduces bugs.

16. What is the function of static?

  1. In the body of a function, a variable declared static maintains its value across calls to the function.
  2. Inside a module (but outside a function), a variable declared static can be accessed by functions used within the module, but not by other functions outside the module. It is a local global variable.
  3. Within a module, a function declared static can only be called by other functions within that module. That is, the function is restricted to the local scope of the module in which it is declared.

17. What does volatile mean and give three different examples.

A variable defined as volatile means that this variable may be changed unexpectedly, so that the compiler will not assume the value of this variable. To be precise, the optimizer must carefully re-read the value of this variable each time it is used, rather than using a backup stored in a register.

Here are a few examples of volatile variables:

  1. Hardware registers of parallel devices (e.g. status registers)

  2. Non-automatic variables that will be accessed in an interrupt service subroutine

  3. Variables shared by several tasks in a multithreaded application

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

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.

19. Can a pointer be volatile? explain why.

Yes. Although this is not very common. An example is when an interrupt service routine modifies a pointer to a buffer .

20. What is wrong with the following function:

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

This code has a trick. The purpose of this code is to return the square of the value pointed to by the pointer *ptr , but 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; 
}

Guess you like

Origin blog.csdn.net/weixin_44035986/article/details/120271452