I'm trying to develop a cipher program that alters someones text input according to a string of 26 char's they can customise. The route I've decided to go is to subtract the individual char values in their input string from another string of the alphabet. The numerical result would then be stored in a separate int array, which will be applied to all future inputs they want to cipher. In order to make it easier for myself, I am capitalising the 26 char user input, but when my code gets to 'j' in the sample user input I've used (the only letter I didn't capitalise for testing purposes) I get a segmentation error.
The code can be found below. My apologies if I have not been sufficiently descriptive. I'm still pretty new to coding, so will answer any questions as best I can.
#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
int main(void)
{
string x = "QWERTYUIOPASDFGHJKLZXCVBNM"; // sample user input for cipher
string y = "ABCDEFGHIjKLMNOPQRSTVUWXYZ";
int code[25];
for(int i = 0; i < 26; ++i)
{
if ((int) y[i] > 90) // For capitalisation
{
y[i] -= 32;
}
code[i] = (int) y[i] - (int) x[i]; // creates cipher array
}
}
stringin your program?int code[25]so the largest valid index forcodeis 24 (the range is 0 to 24). Yourforloop takesito a value of 25, then attempts access tocode[i]which is invalid.stringis just atypedefforchar*, from the infamous Cambridge CS50. When you assign toy[i]you are modifying a static string and that is a must-not in C. Try declaring the variable aschar y[] = "ABC...";.stringwithchar *-- it would be absolutely clear thatxandypoint to constants and therefore you shouldn't modify the thing they point to. If you were taught to usestringthis way, you should seriously try to find a different teacher because they are teaching you things that make coding significantly harder.