string reverse without new array
hi can anybody tell me the error in this?
#include<stdio.h>
int main()
{
char a[]="abcdefgh";
int i=0;
int n=strlen(a);
char *fi开发者_如何学运维rst;
char *second;
char *c;
*first=a[0];
*second=a[7];
for(i=0;i<=n/2;i++)
{
*c=*first;
*first=*second;
*second=*c;
first++;
second--;
}
for(i=0;i<=7;i++)
{
printf("%c",a[i]);
}
}
The problem is these lines:
*first=a[0];
*second=a[7];
I think what you want is to get first
and second
to point to the correct elements, which is:
first = &a[0]; // address of the first element
second = &a[7]; // address of the eighth element
What you have is assigning the value of a[0]
to the address pointed to by first
, which is not initialized. Also, you might as well use n - 1
instead of 7 here, so you don't hardcode the size. Also these lines:
*c=*first;
*first=*second;
*second=*c;
You see, the pointer c
also hasn't been initialized. What you should do is not have c
as a pointer:
char c;
Then use it just like a normal variable:
c = *first;
*first = *second;
*second = c;
And just a design note, you don't need the counter/for-loop. Rather, you know you're done with second
is <= to first
(that is, we're at or have crossed the half-way point):
while (second > first)
Lastly, through some spaces in there! Your code is very condensed and hard to read. Don't be afraid to space things out.
*first=a[0];
The pointer first
isn’t initialized, so you’re assigning to invalid memory.
精彩评论