0

I am having trouble fixing this code and just not having luck with it. I have to use pointer instead of integers to keep track of the position of the array. I keep getting segmentation fault, so I am going out of bounds of the array. Can someone please explain what I am doing wrong. I tried multiple ways to as *(msg + (*count)++) and msg[(*count)++] Edit: Please ignore printf("%d", *(count++)). I was testing what was the value.

#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>

#define N 50

int main()
{   
    int i, j, *count;    char ch, msg[N], msg1[N];    bool flag = true;
    count = 0;
    // Getting user-defined input   
    printf("Enter a massage: ");

     printf("%d", *(count++));
    ch = getchar();   
    while(ch != '\n' || *count == N) { 
;      
        msg[(*count)++] = ch;  //msg[(*count)++]     
        ch = getchar();   
     } // end of while loop

    // Printing user-defined input   
    printf("User-defined input: ");   
    for(count = 0; *(msg+ *count); count++)       
       printf("%c", *(msg+ *count));   
    printf("\nNumber of characters is %d\n", *count);       

    // Sanitiazation of the msg array (i.e., removing special characters)   
    i = 0;   
    for(j = 0; msg[j]; j++) {       
       if(isalpha(msg[j]))           
              msg1[i++] = tolower(msg[j]);   
    } // end of for loop        

   // Palindrome test    
   for(j = 0; msg1[j]; j++) {       
      if(msg1[j] != msg1[i-j-1]) {           
      flag = false;           
      continue;       
      }   
    } // end of for loop       

   // Printing final decision   
   if(flag)         
      printf("Palindrome\n");   
   else       
      printf("Not palindrome\n");               

   return 0;
} // end of main



David Ranieri
  • 39,972
  • 7
  • 52
  • 94
  • You're setting `count` to `NULL`: `count = 0`. Incrementing this will give you addresses of `4`, `8`, `12`, etc. (most likely). Dereferencing `count` is probably your problem. You need to give `count` a valid address, such as `int i, *count = &i;`. – Fiddling Bits May 05 '20 at 18:11
  • @Jared DaRocha It is unclear how you are determining whether a ,message is a palindrome. For example are digits valid characters? – Vlad from Moscow May 05 '20 at 18:18
  • @VladfromMoscow My professor want us to modify his code into pointers instead. I believe it is only alphabetical characters that is being tested. – Jared DaRocha May 05 '20 at 18:27
  • @FiddlingBits I did do what you explained and tested it by seeing which one printed incremented the right way. (*count)++. but it still going out of bounds. – Jared DaRocha May 05 '20 at 18:30

0 Answers0