Very easy begginer question

closed account (o17XLyTq)
Why is my int i equal to the asci code of A, B,C... instead of 1,2,3,4,5,6,7,8 like i had set it to and how do i change it

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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
  #include <stdio.h>
#include <string.h>
#include <iostream>

int main()
{
	
	int i,j;
	char poz[0];
	
	printf("Enter the horizontal position of queen\n");
	gets(poz);
	
	if(poz=="A")
	{
		i=1;
	}
	else if (poz=="B")
	{
		i=2;
	}	
	else if (poz=="C")
	{
		i=3;
	}
	else if (poz=="D")
	{
		i=4;
	}	
	else if (poz=="E")
	{
		i=5;
	}
	else if (poz=="F")
	{
		i=6;
	}
	else if (poz=="G")
	{
		i=7;
	}
	else if (poz=="H")
	{
		i=8;
	}

	
	
	int chess[8][8]={
	{1,2,3,4,5,6,7,8},
	{1,2,3,4,5,6,7,8},
	{1,2,3,4,5,6,7,8},
	{1,2,3,4,5,6,7,8},
	{1,2,3,4,5,6,7,8},
	{1,2,3,4,5,6,7,8},
	{1,2,3,4,5,6,7,8},
	{1,2,3,4,5,6,7,8},
	};
	
	printf("%d", i);
}
Last edited on
It is not. i remains uninitialized because comparisons like poz=="A" are are always false. You compare two pointer which are different. Use strcmp(...) in order to compare the content of poz.
There are many things wrong with this.

For a start, you're defining poz to be an array of zero length, i.e. an array with no elements. Doesn't your compiler warn you about this?

When you use gets to read data into that array, you are - for obvious reasons - putting data into memory beyond the end of the array. This leads to undefined behaviour.

Secondly, you're trying to use the equality comparison operator == to compare C strings. That doesn't work. In fact, what you're doing is comparing the address of your poz array with the addresses of various string literals ("A", "B", etc), which obviously is never going to be equal.

This means that the value of i is never being set. Since you failed to initialise it, what you're getting printed out is undefined.

Also, what is j for?

To fix this:

1) To compare the contents of two C-strings, use the strcmp() function from the standard library.

2) Always initialise your variables to helpful values.

closed account (o17XLyTq)
j is for nothing right now :D my assigment is " Create a program that determines which chess board fields are available to the queen from the field where it is located. The chessboard is presented as a matrix 8x8. Queen's position is entered from the keyboard into [word] [number]. And the result is saved in a string." , So its far from over.

How do i compare if the content of one string is equal for example to "A", i dont have 2 strings to compare with strcmp()
"A" is a C-string.

'A' is a single character.

If you want to compare the user's input to a single character, then why not just use a single character to store that input?
Last edited on
closed account (o17XLyTq)
Thanks i fixed it
Topic archived. No new replies allowed.