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);
        }

}

If you just wish to reverse the order of the lines in the array ...

try this:

/* demo_str_rev.c */


#include <stdio.h>


void str_rev( char* ary[],  int size )
{
    int i, j;
    for( i = 0, j = size-1; i < j; ++ i, --j )
    {
        char* tmp = ary[i];
        ary[i] = ary[j];
        ary[j] = tmp;
    }
}



int main()
{
    int i;
    char* lines[] =
    {
        "To err is human....",
        "But to really mess things up...",
        "One needs to know C!!"
    };

    const int size = sizeof lines / sizeof *lines;

    puts( "BEFORE reversing lines ... " );
    for( i = 0; i < size; ++ i )
         puts( lines[i] );

    str_rev( lines, size );
    puts( "AFTER reversing lines ... " );
    for( i = 0; i < size; ++ i )
         puts( lines[i] );

    return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.