views:

116

answers:

2

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 *first;
    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]);
    }
}
+2  A: 
    *first=a[0];

The pointer first isn’t initialized, so you’re assigning to invalid memory.

jleedev
+5  A: 

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.

GMan
GMan, you da man. Fix first and complain later… you must be a blessing to your office.
Potatoswatter
Jonathan
@Potatoswatter: Heh, thank you. :) No office yet, still in school. :P @Codeguru: No problem. If you find your problem solved, click the check mark on the answer.
GMan
@Potatoswatter, he's a blessing to me, GMan taught me C++ and continues to help improve my coding abilities. He's an excellent classmate :)
Bruce
@Bruce: :3 B'awwwwww. <3
GMan