One of the "C Language Problem series tutorials" variable declaration and initialization __c language

Source: Internet
Author: User

First, the basic type

The size of the 1.c language integer type is not precisely defined, but varies with the type of compiler, and ANSI C guarantees only the minimum size of the data. Char>=8 bit, short>=16 bit, int>=16 bit, long>=32 bit.

2. Therefore, you can define Int16 and int32 with TypeDef, and then define them as Int,short,long according to the actual machine environment. However, the standard header file <inttypes.h> has defined the standard name int16_t,uint32_t, and so on.

Second, the pointer statement

The syntax declared in the 1.c language is

Basic types generate basic types of things

The basic type does not have to be said to produce a symbol of the basic type, including *p,a[10] or F (), indicating that the life variable is a pointer to the base type, an array of primitive types, or a function that returns the base type. So

Char *P1,P2;//P1 is a pointer to char, p1 is a char variable.

2. If the return value of a function is void, the declaration and definition should be written in the same order. For example: Only two of the following cases

① statement: f (); Definition: F () {}② declaration: void F (); Definition: void f () {} (Note: Must not be exchanged for use)

Three, the declaration style

Global variables and functions are defined in a related. c file, and then external declarations are made in. h. In other. c files that need to be used, only the include corresponding. h files is required. (Note: the. c file that defines the variable should also contain the header file, making it easier for the compiler to check definition and life consistency.) )

By the way, the statement reads as follows:

extern int i;

extern int f ();

The definition is as follows:

int i=0;

int F ()

{

return 1;

}

Third, storage type

1.static

(For static usage, you can refer to the static usage method)

For simplicity, all declarations of the same static function or variable must contain a static storage type.

2.extern

Storage type extern is only meaningful for data declarations. For a function, it's just a formatting hint that the definition of a function might be in another function file.

3.auto

No use, already obsolete. It is inherited from the C language's no-type predecessor B language. In the B language, there is no keyword like int that declares that it must contain a storage type. )

Iv. type definition (typedef)

1.typedef defines a new type name, rather than defining a new variable or function.

2.typedef and #define的区别:

It is generally preferable to use a TypeDef, partly because it handles pointer types correctly, and in addition to complying with scope rules.

typedef char *string_t;
#define STRING_D char*
string_t s1,s2;
String_d S3,s4;
S1, S2, and S3 are all defined as char*, but S4 is defined as a char type.
And the use of #define is generally combined with #ifdef to form conditional compilation.

3. You cannot use it before defining a typedef type. If the following code compilation will be an error

typedef struct{
  Char *item;
  Nodeptr Next;  *nodeptr;
Modified Method ①

typedef struct node{
  char *item;
  struct node *next;
} *nodeptr;
Modified Method ②

struct node;
typedef struct node *nodeptr;
struct node{
  char *item;
  Nodeptr Next;
Modified Method ③

struct node{
  char* item;
  struct node *next;
typedef struct node *nodeptr;
4. Define a pair of mutually referenced structures

Method ①

struct a{
  int afield;
  struct b *bpointer;
struct b{
  int bfield;
  struct A * apointer;
Method ②

struct A;
struct B;
typedef struct a *aptr;
typedef struct B * BPTR;
struct a{
  int afield;
  Bptr bpointer;
};
struct b{
  int bfield;
  Aptr apointer;
};

5. Definition of function pointer type

typedef int (*FUNCPTR) ();

The preceding statement defines a type funcptr that represents a pointer to a function with the return value of type int (parameters not indicated).

namely Funcptr fp1,fp2 and Int (*PF1) (), (*PF2) (), the writing is equivalent.

Five, const-qualified words

1. Counter-cases

typedef char *CHARP;
const CHARP p;
Then P is const (not the character that P refers to), just as const int I declares I to be the const reason. The substitution of a typedef is not entirely text-based.
2. Counter-Cases

const int n=5;
int a[n];

Compilation error is
The true meaning of the const qualifier is "read-only", and the object that is used to qualify is usually an object that is run that cannot be assigned a value. Therefore, the value of a const-qualified object is not exactly a true constant and cannot be used as an array dimension, case line label, or similar environment. (Note: in C + + it can be used as a dimension of an array, and so on.) )

The difference between 3.const char *p,char const *P,CHAR *const p

The first two are interchangeable, and they declare a pointer to the constants of the word (that is, you cannot change the character value that you point to).

The third is to declare a pointer constant that points to a character, or you cannot modify the pointer.

You can see that the const is outside the pointer, then "often" is the pointed character; The const is in the pointer, the "regular" is the pointer itself.

Six, the size of the array

1. Determine the size of the local array based on the parameters passed in

Variable-length array (VLA) is introduced in C99, so it is convenient to implement the partial array with indefinite length. But vc++6.0 uses C89, to implement only the malloc () function, and to call the free () function before the function returns.

The example of dynamically assigning a two-dimensional array is as follows:

Method: Allocates an array of pointers and then initializes each pointer to a dynamically allocated row.

① The row address is discontinuous

#include <stdio.h>
void Test (int nrows,int ncolumns);
int main ()
{
    test (4,5);
	System ("pause");
	return 0;
}
void Test (int nrows,int ncolumns)
{
	int **array1=malloc (nrows*sizeof (int *));//allocate pointer array
	int i;
	for (i=0;i<nrows;i++)
	{
		array1[i]=malloc (ncolumns*sizeof (int));	
	}
	array1[nrows-1][ncolumns-1]=314;
	printf ("array1[nrows-1][ncolumns-1] is%d\n", array1[nrows-1][ncolumns-1]);

Output results are


② The row address is continuous

#include <stdio.h>
void Test (int nrows,int ncolumns);
int main ()
{
    test (4,5);
	System ("pause");
	return 0;
}
void Test (int nrows,int ncolumns)
{
	int **array2=malloc (nrows*sizeof (int *));//allocate pointer array
	int i;
	Array2[0]=malloc (nrows*ncolumns*sizeof (int));//Allocate entire box, including line No. 0 for
	(i=1;i<nrows;i++)
	{
		Array2[i] =array2[0]+i*ncolumns;	Assign the first address of each row to the Array2 pointer
	}
	array2[nrows-1][ncolumns-1]=314;
	printf ("array1[nrows-1][ncolumns-1] is%d\n", array2[nrows-1][ncolumns-1]);
Output results are


(Note: The return value of the malloc should be judged in the actual application and the memory freed by the free () function should be called before the function returns.) )

2. Get the size of a global array

In the file1.c

int array[]={1,2,3};
In the FILE2.C

extern int array[];
If you want to use sizeof () to get the size of the array in the file2.c file, it is not possible because sizeof is at compile time and cannot get the size of the array defined in another file.
The solution is to declare an integer variable in file1.c to represent the size of the array.
3. Questions about allocating arrays or structures that are larger than 64K

Standard C does not guarantee that an object can be greater than 32K, or C99 64K. Solutions include:

① uses a linked list or structure pointer instead of a larger array of structures. For example: 1 The method that determines the address discontinuity between rows in the local array according to the incoming parameters.

② If you are using a PC-compatible (based on 8086) system, and you encounter 64K or 640K limitations, consider using the "huge" memory model, either by using extended memory or by extending memory, or by using malloc variant functions Halloc and Farmalloc, or by using the 32-bit " Flat "(flat) editor (for example: DJGPP), or use a DOS extension, or a different operating system.

Vii. initialization

1. For variables that do not show initialization, if the static (static) lifetime (variables declared outside the function and static storage variables) are uninitialized, you can ensure that the shape is initialized to 0, the floating-point type is initialized to 0.0, and the pointer is initialized to NULL.

In the case of an automatic (automatic) lifetime variable (that is, a local variable of a non-static storage type), the value is an indeterminate amount of garbage memory.

(Note: For arrays and structs, initialization is also considered "variable")

#include <stdio.h>
int i;
float F;
char *p;
int main ()
{
	int J;
	static int k;
	printf ("i=%d j=%d k=%d\n", i,j,k);
	printf ("f=%f\n", f);
	printf ("p=%d\n", p);
	System ("pause");
	return 0;
}
Output results are

(Note: Dynamically allocated memory using malloc and realloc may also contain garbage data.) All of the memory obtained with Calloc is zero, but not necessarily useful for pointers and floating-point values. )
2.malloc functions can only initialize an automatic variable (that is, a local non-static variable). If the following program will complain

#include <stdio.h>
Char *p=malloc (a);
int main ()
{return
	0;
}

The following error occurred:
3. Differences in pointer and array initialization

Char a[]= "Hello world!";
Char *p= "Hello world!";
The following program may crash after it is run

#include <stdio.h>
int main ()
{
	char *p= "Hello world!";
	p[1]= ' I ';
	return 0;
}

① as an array initializer (char a[]) that indicates the initial value of the characters in the array.

② in other cases, it will first be converted to an unnamed static character array, which may be stored in read-only memory, which will cause it to not be modified.
4. Character array initialization can be a long string to assign values, but ultimately only the previous part of the string, and there is no ' "' this terminator.

Like what:

Char a[3]= "ABCD";
is legal.
5. Initialization of function pointers

#include <stdio.h>
int test ()
{
	printf ("haha\n");
	return to the
;
int main ()
{
	int (*p) () =test;
	int a=p ();
	printf ("%d\n", a);
	System ("pause");
	return 0;
}
Output results

6. Joint initialization issues

In the original ANSI C, only the first named member of the Union can be initialized.

C99 introduced "Specify initial test" to initialize any member.

Well, that's all for the first lecture, so we'll have to say goodbye next time.









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.