0

I need help solving this problem in my mind so if anyone had a similar problem it would help me a lot.

The task is:Enter an array of strings from the standard input, using the function invert to invert each string. The inverted string must not contain digits. Prototype function is: invert(char **array,int n);

Here' s my code:

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

void processing_string(char *s);
void invert(char **array,int n)
{

   if(n>0)
   {
       processing_string(array[n-1]);
       invert(array,n-1);
   }


}

void processing_string(char *s)
{
   int d=strlen(s);
   for(int i=0;i<d/2;i++)
   {
       char c=s[i];
       s[i]=s[d-i-1];
       s[d-i-1]=c;
   }
   char *t=(char*)calloc(d+1,sizeof(char));
   for(int i=0,j=0;i<d;i++)
   {
       if(s[i]>='0' && s[i]<='9')
       {
           t[j++]=s[i];
       }
   }
   strcpy(s,t);
   free(t);
}
int main()
{
   int n;
   printf("n=");
   scanf("%d",&n);
   char *array[n][20];
   for(int i=0;i<n;i++)
   {
       scanf("%s",array[i][20]);
   }

   invert(array,n);
   for(int i=0;i<n;i++)
   {
      printf("%s",array[i][20]);
   }

   return 0;
}

The problem is that my program breaks, after entering the strings, I don't think I'm entering the strings as I should, and I'm not forwarding them well to the invert function?

Thanks in advance !

Best regards!

IMSoP
  • 89,526
  • 13
  • 117
  • 169

1 Answers1

1

array[i][20] is out-of-range of the 20-element array array[i], so you mustn't read nor write the "element".

Instead of the out-of-range access, you should:

  1. Declare an array of char*
  2. Allocate a buffer and assign to the array.
  3. Read strings to the buffer.

Applying this, your main function will be like this:

int main(void)
{
   int n;
   printf("n=");
   scanf("%d",&n);
   char *array[n];
   for(int i=0;i<n;i++)
   {
       array[i] = malloc(20);
       /* TODO: detect and handle allocation error */
       scanf("%19s",array[i]);
   }

   invert(array,n);
   for(int i=0;i<n;i++)
   {
      printf("%s",array[i]);
   }

   for(int i=0;i<n;i++)
   {
      free(array[i]);
   }
   return 0;
}

Also note that:

  • You should specify the maximum length of strings to read like %19s instead of %s to prevent buffer overrun.
  • Casting results of malloc() family is considered as a bad practice.
MikeCAT
  • 73,922
  • 11
  • 45
  • 70