0

I am new to C,

So I tried to make a program assigning grades according to marks of students. I need to make a char array with the first slot referring to the first student .. etc

The initialization was simple

char grade[n];

Where n is the number of students

to assign values I made a condition comparing the marks in a loop and if the condition is fulfilled this kind of statement is executed :

grade[i] == 'B';

To call the value at the end I used this :

printf("%c", &grade[i]);

Where "i" is the displaying loop control variable.

At the end, strange symbols were displayed. What is the right way to create an array of chars and calling individual "slots" ?

  • 4
    `==` is not an assignment operator. – William Pursell Dec 31 '16 at 04:30
  • 1
    `&grade[i]` is getting the *address* of index `i` in the array, which is likely to be a really big, useless number. Just use `grade[i]` to access the character at index `i` of the array. – Purag Dec 31 '16 at 04:30
  • Possible duplicate of [Pointers in C: when to use the ampersand and the asterisk?](http://stackoverflow.com/questions/2094666/pointers-in-c-when-to-use-the-ampersand-and-the-asterisk) – Purag Dec 31 '16 at 04:31
  • 1
    @Purag - partly. OP also seems to be using the comparison operator (`==`) when assignment (`=`) is intended. – Peter Dec 31 '16 at 04:34
  • Thanks guys .. that really helped me so much .. I am so grateful =) – DarkProfessor Dec 31 '16 at 06:29

3 Answers3

4

Change this

printf("%c", &grade[i]);

to

printf("%c", grade[i]);

And it should work as you expect.

Sush
  • 1,169
  • 1
  • 10
  • 26
  • @user2217482 Can you paste your whole program in the question? We can have a look to see other problems. – Sush Dec 31 '16 at 06:21
3

You print pointer address, don't use & in print.

Orest Savchak
  • 4,529
  • 1
  • 18
  • 27
1

Just use printf("%c", grade[i]) without the "&" address-of operator. You want to print the character at index i, not the address of that character.

Willis Blackburn
  • 8,068
  • 19
  • 36