Click to See Complete Forum and Search --> : A help


am_abbas
March 5th, 2003, 07:16 AM
Hi Gurus,

I would like to know what is wrong in the below code. I am a CAD operator I rarely work in API for small automation.

Thanks and Regards,
Abbas

#include <stdio.h>
main()
{
char *new,*temp,*c;

new="abcdefghijklmnopqrstuvwxyz1234567890";
c=strchr(new,'\0');
while(c>=new)
{
printf("%c",*c);
*temp++=*c--;
}
*temp='\0';
temp++;
printf("%s\n",temp);
printf("\n%s",new);

}

Gabriel Fleseriu
March 5th, 2003, 07:19 AM
"new" is a reserved C++ keyword. You cannot name a variable "new" :)

am_abbas
March 5th, 2003, 07:24 AM
I have changed new to n. But dosen't work. Thanks for your intrest.

Thanks and Regards,
Abbas

dude_1967
March 5th, 2003, 07:35 AM
Are you simply trying to reverse a string? There are standard functions for this. Take a look below.

Sincerely,
Chris.

P.S. Avoid the use of "new" for variable names. This is a keyword in C++.

:)



#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char* argv[])
{
char* cnew = (char*) malloc(256);
char* temp = (char*) malloc(256);

strcpy(cnew, "abcdefghijklmnopqrstuvwxyz1234567890");
strcpy(temp, cnew);

strrev(temp);

printf("%s\n", temp);
printf("\n%s", cnew);

free(cnew);
free(temp);

return 1;
}

am_abbas
March 5th, 2003, 07:45 AM
Hi Chris,

I am just trying to understand why noting is been stored in *temp when I say "*temp=*c;" or I get a error while trying to do so. Could you please explain. Thanks for your intrest.

Thanks and Regards,
Abbas
#include <stdio.h>
main()
{
char *n,*temp,*c;

new="abcdefghijklmnopqrstuvwxyz1234567890";
c=strchr(new,'\0');
while(c>=n)
{
printf("%c",*c);
*temp++=*c--;
}
*temp='\0';
temp++;
printf("%s\n",temp);
printf("\n%s",n);

}

dude_1967
March 5th, 2003, 07:59 AM
In your code you never initialized temp. Then you manipulate temp with the post increment operator. You must first initialize temp befor using it. I think that you want to initialize temp to point to the end of your string new (which you should call cnew or something other than new).

Before your loop, initialize temp to point to the end of cnew and then do your operations.



temp = cnew + strlen(cnew);



Then go into your loop.

Sincerely,
Chris.

:)

P.S. I am using plain old C for this post not C++, since I think you want a solution in C.

dude_1967
March 5th, 2003, 08:35 AM
Sorry, I had made a mistake. You want temp to point to the beginning of cnew and c to point to the end of cnew before entering the loop.

I would aviod using strchr(..., '\0') to find the end of the string and preferably use strlen(...). You might consider initializing cnew with strcpy(...) as shown in my previous post since you do not know exactly how the compiler will allocate the string lietral "abcdefg..., etc" in your sample code.



c = cnew + strlen(cnew);
temp = cnew;

// Now go into the loop...



:)