why the first one works fine while second one shows error. 1.
char *reverse(char *ara)
{
char *ptr1=ara,*ptr2=ara;
}
2.
char *reverse(char *ara)
{
char *ptr1,*ptr2;
*ptr1=ara,*ptr2=ara;
}
where main function looks like this
int main()
{
char ara[100]="Programming";
reverse(ara);
}
The first one is equivalent to:
char *ptr1;
char *ptr2;
ptr1 = ara; // ptr1 points to the same place as ara
ptr2 = ara; // ptr2 points to the same place as ara
while the second is equivalent to:
char *ptr1;
char *ptr2;
*ptr1 = ara; // Problems
*ptr2 = ara; // Problems
Problem 1:
Those lines are compile time problems since *ptr1
and *ptr2
evaluate to char
while the type they are being assigned to is char*
.
Problem 2:
If the compiler were to ignore the error, you will run into run time error since neither ptr1
nor ptr2
point to anything valid and you are using *ptr1
or *ptr2
to assign values to.
A declaration such as char *ptr1;
, says *ptr1
is a char
, meaning ptr1
is a pointer to a char
.
When the declaration includes initialization, as in char *ptr1 = ara;
, it means ptr1
, which is a pointer to char
, is initialized with the value ara
.
In an assignment such as *ptr1 = ara
, *ptr1
means the thing that ptr1
points to. So this assignment is attempting to assign the value ara
, which is a pointer to char
, to the char
that ptr1
points to. Your compiler complains about this because a char
is not a suitable destination for a pointer to char
.
You should be clear about how names look in declarations and how they look in expressions. In a declaration, the name is used with operators to show an example of how it will be used. For example, char foo()
says foo
will be used as a function, so it is a function that returns a char
, and char foo[]
says foo
will be used as an array, so it is an array of char
.
When you use an identifier the same way it appears in a declaration, it forms an expression with the declared type. So, after the declaration char *ptr1
, the expression *ptr1
is a char
. The actual pointer to a char
that was declared is ptr1
, not *ptr1
.
When initialization appears in a declaration, it initializes the declared object ( ptr1
), not the example expression in the declaration (not *ptr1
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.