'the char pointer prints more garbage values if i give string in even length but working correctly for string with odd length...can anyone say why?
"
#include<stdio.h>
#include<string.h>
int main()
{
char string[100]="abbd";
int len=strlen(string);
char *left = &string[0];
char *right = &string[len-1];
char ans[10];
int k = 0;
while(left != right)
{
if(len%2 != 0)
{
if(*left != *right)
{
ans[k++] = *left;
}
}
printf("%c",*left);
left++;
right--;
}
for(int i=k-1;i>=0;i--)
printf("%c",ans[i]);
return 0;
} "/* the code is for to make the string palindrome...
i know it is not fully correct but i need to know why more garbage value is printed for even length string alone */
Solution 1:[1]
Well, grab a pen and paper.
int len=strlen(string);
char *left = &string[0];
char *right = &string[len-1];
.
.
.
while(left != right) { ...
Suppose the string "012345", where each element also represents its own address relative to the start of the array.
at the beginning,
left --> 0 right --> 5First iteration,
left --> 1 right --> 4Second iteration,
left --> 2 right --> 3Third iteration,
left --> 3 right --> 2
Hence, as you can see, left was never equal to right when the string is of even length, the loop condition is never falsified, the pointers kept getting incrementing and decrementing, accessing beyond the range of your array and reading garbage.
Instead try:
while( left < right ) { ...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
