Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - Can I directly assign a value to the data pointed to by the pointer in C language? Why?
Can I directly assign a value to the data pointed to by the pointer in C language? Why?

Yes, but int *p;*p=7; does not work.

Because "the data pointed to by the pointer can be assigned directly", and p here has not pointed to it yet, so it cannot be assigned. This kind of pointer is called "floating pointer", and it cannot be assigned a value.

This works:

int a,*p=&a;*p=7;

In fact, it makes a equal to 7.

Extended information:

Notes

You can also use the assignment operator to assign a value to a pointer variable, but make sure that the two pointer variables are of the same type.

Suppose there is the following variable definition:

int i,j,*p,*q;p=&i;q=&j;

These two sentences will The addresses of variables i and j are assigned to pointer variables p and q respectively;

After executing q=p, this statement is executed. Pointer variables p and q both point to the same variable i, so the pointer variables What is stored in p and q is the address &i of variable i. The variable i is not initialized at this time, only a memory unit is allocated for it.

Note: q=p; and *q=*p

The former assigns a value to the pointer variable q, that is, assigns the address of a variable stored in the pointer variable p to q. Obviously, after assignment, q and p point to the same variable. ?

The latter assigns the value pointed to by p to the variable pointed to by q.

Example:

p=&i;

q=&j;

i=2;

j =3;