3

I am trying to do something as simple as printing the reverse of a string . EXAMPLE :

Hello World! This is me

Needed O/P:

me is This World! Hello

My code goes something like this:

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

int main(){
 char *arr[20] ;
 int i,j;
 int size;
 char *revarr[20];
 printf(" enter the number of words\n");
 scanf("%d",&size);
 for(i=0;i<size;i++)
 scanf("%s",&arr[i]);
 for(i=0;i<size;i++)
 {

    printf("%s\n",&arr[size-1-i]); //overwritten words
    revarr[i]=arr[size-1-i];
 }
 printf(" the reversed sentence is %s\n",(char *)revarr);
}

I except arr[0] , arr[1] etc to be separate entities but on printing and storing them they seem to be overlapping like this : i/p:

Hello World

o/p:

World
HellWorld
the reversed sentence is WorlHell@#$

I can't seem to figure out what is wrong! Thanks in advance!

EDIT : On printing

printf(&arr[0]);
printf(&arr[1]);

I get :

HellWorld
World

What I expected it to print is

Hello
World
3
  • Looks like the OP intended to do so, since j is declared but never used... Commented Dec 24, 2014 at 20:26
  • Even if i try to print(&arr[0]) and print(&arr[1]) i am getting incorrect words! Commented Dec 24, 2014 at 20:26
  • That's not a nested loop, anyway. Commented Dec 24, 2014 at 20:27

4 Answers 4

8

You declared arr and revarr as array of char pointers. You need to dynamically allocate memory for their elements.
Also note that you do not need & in statements

scanf("%s",&arr[i]);  

and

printf("%s\n", &arr[size-1-i]);  
//             ^No need of &  

Here is the modified version of your code. Note that there is no need to use revarr to reverse the string.

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

int main(){
    size_t i, size;
    printf("Enter the number of words\n");
    scanf("%d", &size);
    char *arr[size] ;  // Variable length array. Supported by C99 and latter

    for(i = 0; i < size; i++) 
    {
        arr[i] = malloc(20); // Assumimg words are no longer than 20 characters
        scanf("%s", arr[i]);
    }

    printf("The reversed sentence is:\n");  
    for(i = size-1; i >= 0; i--)  // Run loop in reverse order and print words
        printf("%s ", arr[i]); 
}
Sign up to request clarification or add additional context in comments.

7 Comments

Or, since string.h is included, just use strings, no?
@dodexahedron; No! In C there is no string type.
True, if C. I was in C++ land and thinking std::string.
In my view this is the most elegant solution: given that each word is a separate string entry by OP's post, there is no need for revarr[] or string copying: just a reverse loop.
Straight forward: 1+; However still nitpicking, that i and size should be size_ts.
|
2

You haven't allocated memory for arr[0], arr[1], etc. before using them to read strings in

scanf("%s",&arr[i]);

That is cause for undefined behavior. You need something like:

int main(){
   char *arr[20] ;
   int i,j;
   int size;
   char *revarr[20];
   printf(" enter the number of words\n");
   scanf("%d",&size);
   for(i=0;i<size;i++)
   {
      // Allocate memory.
      // make it large enough to hold the input
      arr[i] = malloc(100);
      scanf("%s", arr[i]);
   }
   for(i=0;i<size;i++)
   {
      revarr[i]=arr[size-1-i];
   }

   printf(" the reversed sentence is: ");
   for(i=0;i<size;i++)
   {
       printf("%s ", revarr[i]);
   }
   printf("\n");


   // Deallocate the memory.
   for(i=0;i<size;i++)
   {
      free(arr[i]);
   }

   return 0;
}

15 Comments

printf(" the reversed sentence is %s\n",(char *)revarr); does not work
...apart from the missing return 0; ;-)
why can't i use typecast to (char *) and then print revarr? is it because of the '\0' scanf will append after every word which will not let me printf the entire statement?
because revarr[] is an array of pointers to each word (string). That is why @RSahu made a loop to print each with for(i=0;i<size;i++) printf("%s ", revarr[i]);
return 0; can be omitted.
|
2

This is a good approach for your problem :

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

int main(int argc, char *argv[])
{
     /* the string line will contain the line of the  input */
     char line[100];
     /* read the string with the function f gets */
     fgets(line,100,stdin);
   /* the tab will contain all the string of the variable  line */
     char *tab[20];
     /* the variable p will point to each string of the  line */
     char *p=NULL;
     /* we extract the strings of the line via the function strtok */
     p=strtok(line," ");
     int nb=-1;
     while (p!=NULL)
     {
         nb++;
         /* we allocate a space memory fo every str ing  */
            tab[nb]=malloc(sizeof(char)*100);
            strcpy(tab[nb],p);
            p=strtok(NULL," ");
     }
     /* there is an exception with the last string of the line we need to take care o f it */
     tab[nb][strlen(tab[nb])-1]='\0';
     int i;
     /* print the strings in reverse or der  */
     for (i=nb;i>=0;i--)
     {
         printf("%s ",tab[i]);
        /* dont forget to free the space memory at the end of the prog ram  */
         free(tab[i]);
     }
     printf("\n");

     return 0;
}

Comments

1

You need the following

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

int main(void) 
{
    size_t size;

    printf( "enter the number of words: " );
    scanf( "%zu", &size );

    char arr[size][20];
    char revarr[size][20];

    for ( size_t i = 0; i < size; i++ ) scanf( "%s", arr[i] );

    printf( "\n" );

    for ( size_t i = 0; i < size; i++ ) strcpy( revarr[i], arr[size-i-1] );

    printf( "the reversed sentence is"  );

    for ( size_t i = 0; i < size; i++ ) printf( " %s", revarr[i] );
    printf( "\n" );

    return 0;
}

If to enter

2
Hello World

then output will be

World Hello

Take into account that the code will be compiled only if your compiler supports C99. Otherwise you have to allocate memory dynamically for character arrays.

As for your code then it has undefined behaviour and in whole is invalid. You did not allocate memory for each element of arrays arr and revarr. You may not assign one array to another. Instead you have to use standard function strcpy and so on.

8 Comments

Yeah the solution looks good for C. Plus for size_t i might have to import a different header file i guess. Thanks!
but I thought that defining variable inside for loop is only for C++! Am I right ?
@joanOfArc In fact it is the best solution because it is more close to your code where you did not allocate dynamically arrays. It is based on variable length arrays. Of course it would better to use fgets but in this case the program would be more complicated.
@user12448 I wrote in my answer that the compiler should support C99. Otherwise some minor changes are needed.
@joanOfArc 20 is the maximum size in bytes of each words. That is you could define for example char word[20]; And you are asking the user how many words you are going to enter. So size is the number of words. As a result you will get char word[size][20]
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.