C typical Q &

Source: Internet
Author: User

1. What is the problem with such initialization? Char * P = malloc (10); the compiler prompts "invalid initialization" cloud.

A: Is this statement a static or non-local variable? Function calls can only appear in the initial formula of automatic variables (I .e. local non-static variables.
Because the static variable address must be determined during compilation, and the memory address requested by malloc () is determined at runtime.

2. * Does P ++ auto-increment P point to the variable P?

A: suffixes ++ and -- operators have higher priority than Prefix operations. Therefore, * P ++ is equivalent to * (p ++, it auto-incrementing P and returns the value pointed to before auto-incrementing p. To increase the value pointed to by P, use (* P) ++. If the order of side effects is irrelevant, use ++ * P.

3. I have a char * pointer pointing to some int variables. I want to skip them. Why does the following code (int *) P) ++ fail?

A: In C, type conversion means "think of these binary bits as another type and treat them accordingly". This is a conversion operator, according to the definition, only one right value (Rvalue) can be generated ). However, the right value cannot be assigned a value or ++ auto-increment. (If the compiler supports such an extension, it is either an error or a non-standard extension intentionally made .) To achieve your goal, you can use: P = (char *) (int *) p + 1); or, because P is of the char * type, directly use P + = sizeof (INT );

4. Is a null pointer the same as an uninitialized pointer?

A: a null pointer is different from an uninitialized pointer in concept: a null pointer ensures that it does not point to any object or function;
The uninitialized pointer may point anywhere.

5. Can I use 0 to represent a null pointer?

A: According to the language definition, constant 0 in the pointer context is converted to a null pointer during compilation. That is to say, during initialization, value assignment, or comparison, if one side is a pointer type value or expression, the compiler can determine that the constant 0 on the other side is a null pointer and generate a correct NULL pointer value. Therefore, the following code segment is completely legal:
Char * p = 0;
If (P! = 0)

However, the parameters passed into the function are not necessarily treated as pointer environments, so the compiler may not be able to recognize the 0 "representation" pointer without any modification.
Generating a null pointer in the context of a function call requires explicit type conversion, and 0 is regarded as a pointer. For example, a UNIX system calls execl to accept variable-length character pointer parameters ending with a null pointer. It should be called correctly as follows:
Execl ("/bin/sh", "sh", "-c", "date", (char *) 0 );
If the (char *) Conversion of the last parameter is omitted, the compiler does not know that this is a null pointer and is passed in as a 0. (Note that many UNIX manuals are incorrect in this example .)

Abstract:
========================================= ======================
| Available 0 without modification | type conversion to be displayed |
| ------------------------ | --------------------------- |
| * Initialization | * function call, with no prototype in the scope |
| * Value assignment | * variable parameters in Variable Parameter Function calls |
| * Comparison |
| * Function call with fixed parameters |
| And has the original type in the scope |
========================================= ======================

There are two simple rules you must follow:
1) when you need a null pointer constant in the source code, use "0" or "null ".
2) if "0" or "null" is used as a parameter in a function call, convert it to the pointer type required by the called function.

6. Since array references are converted into pointers, what is the difference between arr and & arr if arr is an array?

A: The difference is the type:
In standard C, & arr generates a "T-type array" pointer pointing to the entire array.
In all c compilers, the simple reference to the array (excluding the & operator) generates a t pointer type pointer, pointing to the first member of the array.

7. How do I declare an array pointer?

A: Generally, you do not need. When people casually mention the array pointer, they usually think about the pointer to its first element. Consider using a pointer to an array element instead of an array pointer. The array of type T is converted into a pointer of type T, which is very convenient. You can access individual members of the array by using subscript or increment on the result pointer. The real array pointer will skip the entire array when subscript or increment is used. It is usually only useful when operating the array-if there is another use. If you really need to declare a pointer to the entire array, use a statement like "int (* AP) [N. N indicates the size of the array. If the array size is unknown, N can be omitted in principle, but the generated type is "pointer to an array with unknown size", which is useless.

8. When I pass in a two-dimensional array to a function that accepts pointers, the compiler reports an error. What is the problem?

A: rules that convert arrays into pointers cannot be applied recursively. Arrays (two-dimensional arrays in C) are converted into arrays instead of pointers. Array pointers are often confusing and need to be careful; if you pass two arrays to a function:
Int array [nrows] [ncolumns];
F (array );
Then the function declaration must match:
Void F (int A [] [ncolumns])
{...}
Or
Void F (INT (* AP) [ncolumns])/* AP is an array pointer */
{...}
In the first declaration, the compiler performs an implicit conversion from "array" to "array Pointer". The pointer definition in the second form is obvious. Because the called function does not allocate addresses to arrays, it does not need to know the total size, so the number of rows nrows can be omitted. But the array width is still important, so the Column Dimension ncolumns (for three-dimensional or multidimensional arrays, related dimensions) must be retained. If a function has been defined as a pointer that accepts pointers, it is almost certainly meaningless to directly input a two-dimensional array to it.

9. My strcat () won't work. I tried char * S1 = "hello,"; char * S2 = "world! ";
Char * S3 = strcat (S1, S2); but I got a strange result.

A: The main problem here is that the space is not properly allocated for the connection results. C does not provide automatically managed string types. The C compiler only allocates space for objects explicitly mentioned in the source code (for strings, this includes character arrays and string constants ). The programmer must allocate sufficient space for the results of such runtime operations as string connection. It can often be done by declaring an array or calling malloc. Strcat () is not allocated. The second string is attached after the first string. Therefore, one solution is to declare the first string as an array:
Char S1 [20] = "hello ,";
Because strcat () returns the value of the first parameter, in this example, It is S1, and S3 is actually redundant. After strcat () is called, S1 contains the result. The strcat () call in the question actually has two problems: the String constant pointed to by S1, except that the space is not enough to put into the connected string, it is not necessarily writable.

10. What is the correct way to return strings or other sets?

A: The returned pointer must be a statically allocated buffer or a buffer passed by the caller,
Or the memory obtained by using malloc (), but cannot be a local (automatic) array.

11. I have a program that allocates a lot of memory and then releases it. However, from the operating system's perspective, the memory usage does not go back.

A: most implementations of malloc/free do not return the released memory to the operating system, but are reserved for subsequent use of malloc () in the same program.

12. What is the difference between calloc () and malloc? Use the zero-padding function of calloc
All? Can Free () release the memory allocated by calloc (), or does it need a cfree ()?

A: calloc (m, n) is essentially equivalent:
P = malloc (M * n );
Memset (p, 0, M * n );
Zero fill is zero, so it cannot be ensured that a useful NULL pointer value or floating point zero value free () can be safely used to release the memory allocated by calloc.

13. I think there is a problem with my Compiler: I noticed that sizeof ('A') is 2 rather than 1 (I .e., not sizeof (char )).

A: It may be surprising that the character constant in C is of the int type, so sizeof ('A') is sizeof (INT), which is different from C ++.

14. Why is the declaration of extern int F (struct x * P); a strange warning message "structure X declared in the parameter list" reported "?

A: What is quite different from the general scope rules of C language is that the structure declared (or even mentioned) for the first time in the prototype cannot be compatible with other structures in the same source file, it is out of scope when the prototype ends. To solve this problem, put the following statement before the prototype of the same source file:
Struct X;
It provides an incomplete statement of structure X within the scope of the file, so that subsequent statements using structure X can at least determine that they reference the same structure X.

15. I don't understand why I can't use constants in initialization and array dimensions like this: const int n = 5; int A [n];

A: the true meaning of the const qualifier is "read-only". The object defined by const is an object that cannot be assigned a value at runtime (the same time.
Therefore, the value of the object defined by const is not completely a real constant. C and C ++ are different in this regard. If you need a real running time, use the predefined macro # define (or enum ).

16. Can I define main () as void to avoid disturbing the warning of "no return value for main?

A: No. Main () must be declared as return int, and there is no parameter or two parameters of the appropriate type are accepted. If you call exit () but still have warning information, you may need to insert a redundant return statement (or use some "not reached" command, if any ). Many books use void main () in the example and claim that this is correct. But they are wrong.

17. # What is Pragma and what is its use?

A: # The pragam directive provides a single clearly-defined "rescue capsule" that can be used for various (unportable) Control and scaling purposes: source code table control, structure compression, warning removal (like lint's old/* notreached */comment), and so on.

 

18. What does "# pragma once" mean? I saw it in some header files.

A: This is an extension implemented by some preprocessors to enable header file self-identification. It is equivalent to the # ifndef technique, but it is less portable.

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.