Using chars as int, change int, and usit again as char.

I'm pretty new to programming. I made this small program (which isn't working yet) to read a message from console, change some ASCII-table values, and print it. I have made several mistakes, can't find where. I don't get any errors or warnings, compiled with -std=c99.
Thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <stdio.h>

int main(){
	int maxsize;
	printf("How long is your message?\n");
	scanf("%d",&maxsize);
	int iinput[maxsize], ioutput[maxsize], key, c;
	char cinput[maxsize], coutput[maxsize];
	
	printf("What is the message you want to (de)code?\n");
	scanf("%s",cinput);
	for(int i=0;i<maxsize;i++){
		iinput[i]=(int)cinput[i];
	}
	printf("Thank you. ");
	printf("What is your key?\n");
	scanf("%d",&key);
	lchoice:
	printf("1 for coding, 2 for decoding.\n");
	scanf("%d",&c);
	switch (c)
	{
		case 1:
			for(int j=0;j<maxsize;j++){
				ioutput[j]=iinput[j]+key;
			}
			for(int k=0;k<maxsize;k++){
				coutput[k]=(char)ioutput[k];
			}
			break;
		case 2:
			for(int j=0;j<maxsize;j++){
				ioutput[j]=iinput[j]-key;
			}
			for(int k=0;k<maxsize;k++){
				coutput[k]=(char)ioutput[k];
			}
			break;
		default:
			printf("You did not enter 1 or 2.\n");
			goto lchoice;
	}
	printf("This is the coded message:\n");
	printf("%s\n",coutput);
	system("pause");
	return(0);
}
Last edited on
There's a segfault in your use of scanf.

scanf("%d", &maxsize);

You need to send the address of maxsize instead of copying its value. These are C-functions (I think), and thus, there are no references. Alternatively you can use C++ std::cin, unless you insist on using C.
Thanks a lot so far. However, this was only my first mistake. My current output is something like this:

How long is your message?
5
What is the message you want to (de)code?
Hello
Thank you. What is your key?
1
1 for coding, 2 for decoding.
1
This is the coded message:
Ifmmp_@

I don't understand the final output, the "coded message". At least i should expect something with 5 characters.
Last edited on
Topic archived. No new replies allowed.