c programming -reversing individual words in a string
#include<stdio.h>
#include<conio.h>
#include<string.h>
main(){
char *c;
char *y;
int len=strlen(c);
int i,k=0,j,m=0,t;
clrscr();
printf("Enter the string :");
gets(c);
printf("%s",c);
for(i=0;i<=len;i++)
{
if(c[i]==' '|| c[i]=='\0')
{
for(j=i-1;j>=m;j--)
{
y[k]=c[j];
k++;
}
y[k]=' ';
m=k;
k++;
}
}
y[len]='\0';
for(i=0;i<len;i++)
printf("%c",y[i]);
getch();
}
开发者_StackOverflow中文版
This program is to reverse the words in a string that is trying by me for a long time.i think logic i wrote is correct and i am getting different outputs each time.. some times output of previous execution will append in the next output. can any one tell me where is the mistake
some times i am getting correct output with one letter missing.
one more thing i am adding when i am printing directly "y as an array it is coming, if i am trying to give as pointer it is not coming i mean
printf("%s",y); //output not coming properly
for(i=0;i
i want to know the exact difference
This:
char *c;
char *y;
int len=strlen(c);
is an almost certain recipe for disaster: c
is an uninitialised pointer and you are passing it to strlen
. The best that you can hope for is an immediate core dump.
You need to fix that first, if only with the kludge:
c = malloc(1000);
Ther are better ways but probably the skill level where you're aiming with that code (not trying to be offensive there, just stating that this is CS101-level stuff where advanced user input functions are probably not needed).
Problems I see right away is that you not initializing your variables and not allocating any memory for the string buffer.
char *c;
int len=strlen(c);
c
in this case is not initialized and calculating the length of the string it points to would result in unpredictable behavior.
Then you do
gets(c);
c
should point to some memory allocated with either malloc
and friends or to an array (like c[1024]
).
y
is not initialized either.
First allocate the required amount of memory to y. You are getting the result from previous execution because the previously allocated memory could be reused. So free up the memory when not needed and allocate when needed.
精彩评论