Did a tutorial on arrays and pointers today and wrote this little program.
#
Code:
include <stdio.h>
int main()
{
int position;
int length;
char arr [5];
char *cptr;
cptr = arr;
printf ("Please enter a character array: ");
scanf ("%s", &arr);
length = strlen(arr);
while (length > 5)
{
printf ("Too big, please try again: ");
scanf ("%s", &arr);
length = strlen(arr);
}
printf ("Which letter would you like to point to? ");
scanf ("%d", &position);
position = position - 1;
printf("%c\n", arr[position]);
return 0;
}
It sort of works! If I enter a string of 5 characters I get the correct answer but get a run time error as well stating the stack around arr is corrupt. If i enter a string larger than 5 characters i go into the loop as expected but if I then enter a string of less than 5 characters, again i get the right answer and the same run time erros. Any suggestions?