[Collection] classical C/C ++ interview questions (6)

Source: Internet
Author: User

1) What is pre-compilation and when pre-compilation is required:

Always use a large scale that is not changed frequentlyCodeBody.

ProgramConsists of multiple modules. All modules use a set of standard inclusion files and the same compilation options. In this case, all contained files can be precompiled into a precompiled header.

2) char * const P;
Char const * P
Const char * P

What are the differences between the three above?

Char * const P; // constant pointer. The value of P cannot be modified.
Char const * P; // pointer to a constant. The constant value cannot be changed.
Const char * P; // and char const * P

3) Char str1 [] = "ABC ";
Char str2 [] = "ABC ";

Const char str3 [] = "ABC ";
Const char str4 [] = "ABC ";

Const char * str5 = "ABC ";
Const char * str6 = "ABC ";

Char * str7 = "ABC ";
Char * str8 = "ABC ";

Cout <(str1 = str2) <Endl;
Cout <(str3 = str4) <Endl;
Cout <(str5 = str6) <Endl;

Cout <(str7 = str8) <Endl;

Result: 0 0 1 1

Answer: str1, str2, str3, and str4 are array variables with their own memory space. str5, str6, str7, and str8 are pointers pointing to the same constant area.

4) Is there a problem with the usage of two sizeof in the following code?

Void uppercase (char STR []) // converts lowercase letters in STR to uppercase letters.
{
For (size_t I = 0; I <sizeof (STR)/sizeof (STR [0]); ++ I)
If ('A' <= STR [I] & STR [I] <= 'Z ')
STR [I]-= ('A'-'A ');
}
Char STR [] = "ABCDE ";
Cout <"str character length:" <sizeof (STR)/sizeof (STR [0]) <Endl;
Uppercase (STR );
Cout <STR <Endl;

A: There is a problem with sizeof in the function. According to the syntax, sizeof, for example, is used as an array, can only measure the size of a static array, and cannot detect the dynamically allocated or external array size. The STR outside the function is a static defined array, so its size is 6. The STR in the function is actually a pointer to a string without any additional array-related information, therefore, sizeof only acts as a pointer, and a pointer is 4 bytes, SO 4 is returned.

5) What is the pointer of a 32-bit machine?

You only need to check the number of bits in the address bus. Machines later than 80386 have 32 data buses. Therefore, the number of digits of the pointer is 4 bytes.

6) Main ()
{
Int A [5] = {1, 2, 3, 4, 5 };
Int * PTR = (int *) (& A + 1 );
Printf ("% d, % d", * (a + 1), * (ptr-1 ));
}

Output: 2, 5

* (A + 1) is a [1], * (ptr-1) is a [4], the execution result is 2, 5
& A + 1 is not the first address + 1. The system will consider that the offset of adding an array a is the offset of an array (in this example, It is 5 Int values)
Int * PTR = (int *) (& A + 1 );
Then PTR is actually & (A [5]), that is, a + 5

The reason is as follows:

& A is an array pointer and its type is int (*) [5];
The pointer plus 1 should add a certain value according to the pointer type, and the size of the pointer plus 1 of different types will be different.
A is an int array pointer with a length of 5, so you need to add 5 * sizeof (INT)
Therefore, PTR is actually a [5].
But the PRT and (& A + 1) types are different (this is important)
So the prt-1 will only subtract sizeof (int *)
A, & A has the same address but different meanings. A is the first address of the array, that is, the address of a [0], and a is the first address of the object (array, A + 1 is the address of the next element of the array, that is, a [1]. & A + 1 is the address of the next object, that is, a [5].

7) Is there any problem with the following code:

Int main ()
{
Char;
Char * STR = &;
Strcpy (STR, "hello ");
Printf (STR );
Return 0;
}

If no memory space is allocated for STR, an exception occurs. The problem is that a string is copied into the address indicated by a character variable pointer. Although the results can be correctly output, the program crashes because internal read/write is performed out of the border.

8)
Char * s = "AAA ";
Printf ("% s", S );
S [0] = 'B ';
Printf ("% s", S );

What's wrong?

"AAA" is a String constant. S is a pointer pointing to this string constant, so there is a problem when declaring S.

Cosnt char * s = "AAA ";

Then, because it is a constant, it is illegal to assign values to s [0.

9) write a "standard" macro, which inputs two parameters and returns a smaller one.

. # Define min (x, y) (x)> (y )? (Y) :( X) // It does not end;

10) infinite loops are often used in embedded systems. How do you use C to write an infinite loop.

While (1) {} or (;;)
Software Development Network www.mscto.cn
11) What is the role of the keyword static?

Define static variables

12) What is the meaning of the keyword const?

Variable that cannot be modified by a constant.

13) What does the keyword volatile mean? And give three different examples?

It is prompted that the value of the compiler object may change without being monitored by the compiler.

14) What is int (* s [10]) (INT?

INT (* s [10]) (INT) function pointer array, each Pointer Points to an int func (int param) function.

15) there are the following expressions:

Int A = 248; B = 4;
Int const c = 21;
Const int * D = &;
Int * const E = & B;
Int const * f const = &;

Which of the following expressions will be forbidden by the compiler? Why?

* C = 32; D = & B; * D = 43; E = 34; E = & A; F = 0x321f;
* C What is this? No
* D: Const. No.
E = & A: const forbidden.
Const * f const = & A; forbidden

16) exchange the values of two variables without the third variable. That is, a = 3, B = 5, after the exchange, A = 5, B = 3;

There are two solutions: one is to use ArithmeticAlgorithm, A ^ (exclusive or)
A = A + B;
B = A-B;
A = A-B;
Or
A = a ^ B; // only int, Char ..
B = a ^ B;
A = a ^ B;
Or
A ^ = B ^ =;

17) What is the difference between struct in C and C ++?

The main difference between struct in C and C ++ is that struct in C cannot contain member functions, while struct in C ++ can. In C ++, the main difference between struct and class is that the default access permission is different. struct is public by default, while class is private by default.

18) # include <stdio. h>
# Include <stdlib. h>
Void getmemory (char * P)
{
P = (char *) malloc (100 );
Strcpy (P, "Hello World ");
}
Int main ()
{
Char * STR = NULL;
Getmemory (STR );
Printf ("% s/n", STR );
Free (STR );
Return 0;
}

The program crashes. the malloc in getmemory cannot return dynamic memory. Free () is dangerous for STR operations.

19) Char szstr [10];
Strcpy (szstr, "0123456789 ");
What results are generated? Why?
 
Invalid OS due to different lengths

20) list the synchronization mechanisms of several processes and compare their advantages and disadvantages.

Atomic operation
Semaphore mechanism
Spin lock
Management, integration, Distributed System

21) communication between processes

Shared Storage System
Message Transmission System
Pipelines: Based on file systems

22) Cause of process deadlock

Illegal resource competition and process Promotion order

23) Four Conditions for deadlock

Mutual Exclusion, request persistence, non-deprivation, loop

24) deadlock handling

Ostrich policy, prevention policy, avoidance policy, detection and deadlock Removal

25) What are the Process Scheduling Policies in the operating system?

FCFS (service first), priority, time slice rotation, multi-level feedback

26) What are the differences between static and non-static members of a class?

Each class has only one static member, and each object has one non-static member.

27) How are pure virtual functions defined? What should I pay attention to when using it?

Virtual void F () = 0;
Yes, the subclass must be implemented

28) differences between arrays and linked lists

Array: sequential data storage, fixed size
Connected tables: data can be stored randomly and the size can be dynamically changed.

29) What is the layer-7 model of ISO? What layer does TCP/UDP belong? What are the advantages and disadvantages of TCP/UDP?

Application Layer
Presentation Layer
Session Layer
Transport Layer
Network Layer
Physical Link Layer
Physical Layer
TCP/UDP belongs to the transport layer
The TCP Service provides data stream transmission, reliability, effective traffic control, full duplex operations, and Multiplexing technologies.
Unlike TCP, UDP does not provide reliable IP protocol mechanisms, stream control, and error recovery functions. Because UDP is relatively simple, the UDP header contains a few bytes, which consumes less than the TCP load.
TCP: provides stable transmission services with traffic control. The disadvantage is that the packet header is large and the redundancy is poor.
UDP: it does not provide stable services, with a small packet header and low overhead.

30) (void *) PTR and (* (void **) PTR have the same results?
Where PTR is the same pointer (void *) PTR and (* (void **) PTR values are the same

32)
Int main ()
{
Int x = 3;
Printf ("% d", X );
Return 1;
}

Why does 1 be returned if the function is not called by other functions?

In Mian, the C standard assumes that 0 indicates successful, and a non-0 value indicates an error. The specific value is the specific error information in a certain project.

33) to assign a value to the absolute address 0x100000, we can use (unsigned int *) 0x100000 = 1234. What should we do if we want the program to jump to the absolute address 0 x for execution?

* (Void (*) () 0x100000 )();
First, we need to forcibly convert 0x100000 into a function pointer, that is:
(Void (*) () 0x100000.
Then call it:
* (Void (*) () 0x100000 )();
You can see more intuitively with typedef:
Typedef void (*) () voidfuncptr;
* (Voidfuncptr) 0x100000 )();

34) an array table is known, and the number of data elements is defined by a macro.

# Define ntbl
# Define ntbl (sizeof (table)/sizeof (Table [0])

35) What are the differences between threads and processes? Does a thread have the same stack? Does the DLL have an independent stack?

The process is dead, but only a collection of resources. Real program execution is completed by threads. When the program starts, the operating system creates a main thread for you.

Each thread has its own stack. Is there an independent stack in the DLL?

This question is hard to answer, or is there a problem. Because the code in the DLL is executed by some threads, only the thread has a stack. If the code in the DLL is called by the thread in the EXE, does it mean that the DLL does not have its own stack? If the DLL code is executed by a thread created by the DLL itself, does the DLL have an independent stack?

The above is about the stack. For the heap, if each dll has its own heap, it is best to delete it from the DLL if it is dynamically allocated from the DLL, if you allocate memory from the DLL and delete it in the EXE or another DLL, it is very likely that the program will crash.

36) unsigned short a = 10;
Printf ("~ A = % u \ n ",~ A );

Char c = 128;
Printf ("c = % d \ n", C );

How much output? And analysis process

Question 1 ,~ A = 0xfffffff5; int value:-11, but uint is output. Therefore, output 4294967285

The second question is c = 0x10. The output is int, the highest bit is 1, and it is a negative number. Therefore, the value of 0x00 is 128, so the output is-128.
These two questions are all about the highest bit processing when binary is converted to int or uint.

37) analyze the following program:

Void getmemory (char ** P, int num)
{
* P = (char *) malloc (Num );
}
Int main ()
{
Char * STR = NULL;
Getmemory (& STR, 100 );
Strcpy (STR, "hello ");
Free (STR );
If (STR! = NULL)
{
Strcpy (STR, "world ");
}
Printf ("\ n str is % s", STR); www.mscto.com
Getchar ();
}

What is the output result?

Output STR is world.

Free is only the memory space pointed to by the released STR, and its value still exists. So after free, there is a good habit of converting STR = NULL.
At this time, the memory of the STR pointing to the space has been recycled. If there is still a space allocation operation before the output statement, the storage space may be reassigned to other variables,
Although this program does have a big problem (as you have already mentioned above), it usually prints out world.
This is because memory management in a process is generally not completed by the operating system, but by the database function itself.

When you malloc a piece of memory, the management library applies for a piece of space from the operating system (which may be larger than the one you applied ), then, record some management information in the space (usually before the memory you applied for) and return the available memory address. However, when the memory is released, the management database usually does not return the memory to the operating system, so you can continue to access this address.

Why is Char A [10], strlen (a) equal to 15? Running result

38) # include "stdio. H"
# Include "string. H"

Void main ()
{
Char AA [10];
Printf ("% d", strlen (AA ));
}

Sizeof () is irrelevant to initial initialization;
Strlen () is related to initialization.

39) Char (* Str) [20];/* STR is an array pointer, that is, a pointer to an array .*/
Char * STR [20];/* STR is a pointer array whose elements are pointer-type data .*/

40) long a = 0x801010;
A + 5 =?
0x801010 in binary format: "1000 0000 0001 0000 0001 0000", the decimal value is 8392720, and the addition of 5 is 8392725.

41) given Structure
Struct
{
Char T: 4;
Char K: 4;
Unsigned short I: 8;
Unsigned long m;
};

Question sizeof (A) =?

Given Structure
Struct
{
Char T: 4; 4 characters
Char K: 4; 4 digits
Unsigned short I: 8; 8 bits
Unsigned long m; // offset of 2 bytes to ensure 4-byte alignment
}; // A total of 8 bytes

42) Is there any error in adding a number to the function implementation below? Please correct.
Int add_n (int n)
{
Static int I = 100;
I + = N;
Return I;
}

If you cannot get the correct result for the second call, do you write a function to call it once? The problem is static?

43) analyze
# Include <iostream. h>
# Include <string. h>
# Include <malloc. h>
# Include <stdio. h>
# Include <stdlib. h>
# Include <memory. h>
Typedef struct AA
{
Int B1: 5;
Int B2: 2;
} AA;
Void main ()
{
Aa aa;
Char CC [100];
Strcpy (CC, "0123456789 abcdefghijklmnopqrstuvwxyz ");
Memcpy (& aa, CC, sizeof (AA ));
Cout <AA. B1 <Endl;
Cout <AA. b2 <Endl;
}

The answer is-16 and 1.

First, the size of sizeof (AA) is 4, and B1 and B2 occupy 5bit and 2bit respectively. after strcpy and memcpy, the four bytes of AA are stored in the following ASC codes:, that is, bytes, and. Therefore, the last step is as follows: the first five digits of the four bytes are displayed, and the second digits are 10000, and 01, respectively, because int has positive and negative points.

So: the answer is-16 and 1.

44) returns the function value. input x = 9999;
Int func (X)
{
Int countx = 0;
While (X)
{
Countx ++;
X = x & (x-1 );
}
Return countx;
}

What are the results?

Knowing how many 1 functions are included in the binary value of 9999, and there are 9999 = 9x1024 + 512 + 256 + 15

9 × 1024 contains 2 numbers of 1;
512 contains 1 of 1;
256 contains 1 of 1;
The number of 1 contained in 15 is 4, and the software development network is www.mscto.com.
Therefore, the total number of 1 is 8, and the result is 8.
1000-1 = 0111, which is the inverse of the original number. This is the principle.
Using this method to calculate the number of 1 is very efficient.
You do not have to shift one by one. The minimum number of cycles.

For int A, B, and C, write the function to implement c = a + B. The data type cannot be changed. For example, to change C to long int, the key is how to handle overflow.
Bool add (int A, int B, int * C)
{
* C = A + B;
Return (a> 0 & B> 0 & (* C <A | * C <B) | (A <0 & B <0 & (* C> A | * C> B )));
}

45) Analysis:
Struct bit
{
Int A: 3;
Int B: 2;
Int C: 3;
};
Int main ()
{
Bit s;
Char * c = (char *) & S;
Cout <sizeof (BIT) <Endl;
* C = 0x99;
Cout <S. A <Endl <S. B <Endl <S. C <Endl;
Int A =-1;
Printf ("% x", );
Return 0;
}

Why is output
4
1
-1
-4
Ffffffff

Because 0x99 indicates 100 11 001, A = 001, B = 11, c = 100 in the memory. When C is a qualified number, c = 100, the highest 1 indicates that C is a negative number, and the negative number is indicated by a supplementary code on the computer, so c =-4; similarly, B =-1; when C is qualified, c = 100, that is, c = 4, and B = 3.

46) Bit domain:

When storing some information, it does not need to occupy a full byte, but only needs to occupy a few or one binary bit. For example, when storing a switch value, there are only two States: 0 and 1. Use one binary digit. To save storage space and simplify processing, the C language also provides a data structure called "bit domain" or "bit segment ". The so-called "bit field" refers to dividing the binary character in a byte into several different regions and showing the digits of each region. Each domain has a domain name, which allows operations by domain name in the program. In this way, several different objects can be represented by a byte binary field. 1. Definition of a bit field and description of a bit field variable the definition of a bit field is similar to that of a structure, in the form:

Struct bit domain structure name {bit domain list}, where the bit domain list is in the form of: type description Character Domain Name: Bit domain Length

For example:
Struct BS
{
Int A: 8;
Int B: 2;
Int C: 6;
};

The description of bitfield variables is the same as that of structure variables. You can first define and then describe, and define or directly describe these three methods. For example:
Struct BS
{
Int A: 8;
Int B: 2;
Int C: 6;
} Data;

It indicates that data is a BS variable, which occupies two bytes in total. Where a occupies 8 places, B occupies 2 places, and C occupies 6 places. The definitions of bit domains are described as follows:

A single-byte field must be stored in the same byte, and cannot span two bytes. If the remaining space of one byte is insufficient to store another domain, it should be stored from the next unit. You can also intentionally start a domain from the next unit. For example:

Struct BS
{
Unsigned A: 4
Unsigned: 0/* airspace */
Unsigned B: 4/* stored from the next unit */
Unsigned C: 4
}

In the definition of this bit field, a occupies 4 bits in the first byte, And the last 4 bits enter 0 to indicate that it is not used. B starts from the second byte and occupies 4 bits, and C occupies 4 bits.

Because the bit field cannot span two bytes, the length of the bit field cannot exceed the length of one byte, that is, it cannot exceed 8-bit binary.

A bit domain can be a non-bit domain name. In this case, it is only used for filling or adjusting the position. An anonymous domain cannot be used. For example:

Struct K
{
Int A: 1
INT: 2/* The two digits cannot be used */
Int B: 3
Int C: 2
};

From the above analysis, we can see that the bit field is essentially a structure type, but its members are allocated by binary.

The usage of bit domains is the same as that of structure members. The general form is: Bit domain variable name? Bit domain names can be output in various formats.

Main ()
{
Struct BS
{
Unsigned A: 1;
Unsigned B: 3;
Unsigned C: 4;
}
Bit, * pbit;
Bit. A = 1;
Bit. B = 7;
Bit. c = 15;
PRI

47) correction:
# Include <stdio. h>
Int main (void)
{
Int ** P;
Int arr [100];
P = & arr;
Return 0;
}

A: Wrong. The pointer type is different. Int ** P; // second-level pointer & arr; // you get the pointer pointing to the array with the first dimension of 100.

# Include <stdio. h>
Int main (void)
{
Int ** P, * q;
Int arr [100];
Q = arr;
P = & Q;
Return 0;
}

48) What are the following errors or effects after the program is executed:

# Deprecision Max 255
Int main ()
{
Unsigned char a [Max], I; // I is defined as unsigned char
For (I = 0; I <= max; I ++)
A [I] = I;
Return 0;
}

Answer: Infinite Loop and array out-of-bounds access (C/C ++ does not carry out array out-of-bounds check) max = 255 array a subscript range: 0 .. MAX-1, this is one ..
Second. when I cycles to 255, A [255] = 255 is executed in the loop. This sentence is correct .. however, when the for (I = 0; I <= max; I ++) Statement is returned, the unsigned char value range is (0 .. 255), after I ++, I is 0 again .. infinite Loop.

49) struct name1
{
Char STR;
Short X;
Int num;
}
Struct name2
{
Char STR;
Int num;
Short X;
}

Sizeof (struct name1) = 8, sizeof (struct name2) = 12

In the second structure, to ensure that num is aligned by four bytes, a space of three bytes must be set aside after Char. In addition, to ensure the natural alignment of the entire structure (4-byte alignment here ), add 2 bytes after X, which is 12 bytes.

50) intel:

Two static variables with the same name are used in the C files a. C and B. C. Will there be problems during compilation? Where will these two static variables be stored (stack, stack, or other static variables )?
Static global variable indicates that this variable is only meaningful in this module and does not affect other modules. They are all placed in the Data zone, but the compiler names them differently. To make variables meaningful in other modules, use the extern keyword.

51) struct S1
{
Int I: 8;
Int J: 4;
Int A: 3;
Double B;
};

Struct S2
{
Int I: 8;
Int J: 4;
Double B;
Int A: 3;
};

Printf ("sizeof (S1) = % d \ n", sizeof (S1 ));
Printf ("sizeof (S2) = % d \ n", sizeof (S2 ));
Result: 16, 24
First struct S1
{
Int I: 8;
Int J: 4;
Int A: 3;
Double B;
};

Theoretically, I occupies 8 bytes at the position relative to 0, and then J is at the position relative to a byte, because the number of bytes in a position is a multiple of four bits, there is no need to align and put it there, and then there is a, which should be at the position of the multiples of three bits, therefore, we need to move one byte, and put it down at the 15-bit position. Currently, the total number is 18 BITs, which is converted to 2 bits. Because double is 8 bytes, therefore, we need to put it down at the position of 8 bytes relative to 0. Therefore, the position from 18 bits to 8 bytes is ignored and placed directly at the position of 8 bytes. Therefore, the total size is 16 bytes.

At the end of the second article, we will compare whether it is a multiple of the largest data in the structure, if not, it will be a multiple of the largest data.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.