Hello everyone! this is a code to reverse strings of a array of char ptr. I am passing the char* array, dynamically allocating memory to reverse and link with the char* array. The print it gives in the str_rev() are perfect. But when I print same thing in main(), it prints randomly. and strangely output is varying from compiler to compiler. Please help me finding out what have I done wrong.
Thanks a lot !
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void str_rev(char *[],int);
int main()
{
int limit = 3,i;
char *s[ ] = {
"To err is human...",
"But to really mess things up...",
"One needs to know C!!"
};
str_rev(s,limit);
printf("main= %d\n",strlen(s[0]));
for(i=0;i<3;i++)
{
printf("Final= %s \n",s[i]);
}
return 0;
}
void str_rev(char *p[],int limit)
{
int i=0,j=0,k=0;
char temp[50];
char *new;
for(i=0;i<limit;i++)
{
//strcpy(temp,p[i]);
j = strlen(p[i])-1;
// printf("\n strlen= %d\n",j);
for(j,k=0;j>=0;--j,++k)
{
temp[k]=p[i][j];
}
temp[k] = '\0';
new = malloc(j+2);
strcpy(new,temp);
p[i] = new;
printf("p[i]= %s\n",p[i]);
printf("\n temp= %s ------------------------- new= %s \n",temp,new);
}
}