0

This is obviously a school assignment. However, with few people to ask for help due to the Corona-outbreak I am reaching out to you for help as am novice and have tried for hours. There is obviously something key with pointers that I am missing.

So, the challenge is to write a program that is letting the user manipulate a pointer through a menu. The pointer should print what it points to after each choice has been made. To start off, the pointer is pointing at the first character of the string e.g. "W" (Washington), and if choice 1 is made by the user the pointer should point at "a" etc. A classic switch case scenario.

It is not allowed for the pointer to point out of the allocated memory.

The code below is not working properly. When I execute the program and choose alternative 1 it says "Dereference of out-of-bounds pointer: 1 bytes past end of array". I need help to interpret this, an explanation of what I might have missed and ideally a few comments for improvements.

Thank you!

#include <stdio.h>


int main (void){

int count, option;
     
char text[10] = "Washington";

char *my_pointer = text;   /* Pointer which points to the beginning of text (string) */

count = 0;

/* Letting the user manipulate the pointer through the menu. The pointer should print what it points to. */ 

   do{
      printf("The text string is: %s\n\n", text);
      printf("The pointer points to %c choose an operation:\n", *my_pointer);
      printf("MENU\n");
      printf("1. Plus 1\n");       /* Increment the pointer - one step to the left */ 
      printf("2. Minus 1\n");      /* Decrement the pointer - one step to the right */
      printf("3. End Program\n");
      scanf("%d", &option);

      switch(option){
         case 1:
         while(count < 10)
         {
         my_pointer++;
         count++;
         }
         break;

         case 2:
         while(count < 10)
         {
         my_pointer--;
         count--;
         }
         break;

         case 3:
         printf("Program Ends");
         break;

         default:printf("\n Wrong input, choose 1 - 4.\n");
         }

      }while (option != 3);

      return 0;
}´´´

1 Answers1

0

Misc bugs:

  • In case 2 you need to check the lower bound (zero) not the upper bound (10).
  • The while loops inside case 1 and 2 should be if statements.
  • You seem to print the character when it is pointing at offset + 10 which is 1 beyond the end of the array.
  • char text[10] = "Washington"; doesn't allocate room for null termination, see How should character arrays be used as strings?
Lundin
  • 195,001
  • 40
  • 254
  • 396