0

I don't know what's the problem with this piece of code, I'm just getting a random result here:

#include <stdio.h>
#include <conio.h>
int main() {
    char arr[3][2] = {{'z','a'},{'e','r'},{'x','v'}};
    int i;
    scanf("%d",&i);
    printf("%c",*(arr+i));
    getch();
}

Thanks

4
  • What are you trying to do? Commented Mar 24, 2014 at 23:59
  • What do you expect *(arr+i) to produce? Commented Mar 24, 2014 at 23:59
  • When I give "i" the value 0 it needs to print 'z' , value "1" it needs to print 'a' ...etc Commented Mar 25, 2014 at 0:03
  • OT: Not what I call "Memory safe code" by the way. /OT Commented Mar 25, 2014 at 13:38

2 Answers 2

1

First of all it is not clear what you are trying to do. I can only suggest to change statement

printf("%c",*(arr+i));

the following way

printf("%c",**(arr+i));

In this case if i will be in the range 0 - 2 then this statement will output the first character of the corresponding row. For example for i equal tp 1 the output will be

e

if you want to output any character in the array using i as an index then use

printf("%c", *( *arr + i ));

Or

for ( int i = 0; i < 6; i++ ) printf("%c", *( *arr + i ));
Sign up to request clarification or add additional context in comments.

5 Comments

What if I want to print 'a' ?
@JohnnyCat Then you would enter the value 0 for i and do *(*(arr + i) + 1) or arr[i][1].
I guess arr is a pointer to the whole array and *arr is a pointer to the first row. That's why when we use **(arr+i) it will access the first element of the "i" row.
@JohnnyCat In expressions arr has type char ( * )[2] that is pointer to char [2]. *arr means the array char[2] In expressions it is converted to char * So the expression *arr + i has type char *
Maybe you wanted arr[i/2][i%2] . Using the *(+) notation seems more confusing than [][] to me.
0

If you provide the value 0 then it will give the result assign the address of zero-th item and if you provide the 1 it will print the address of 1st item

zero-th item  = {'z','a'},
first item = {'e','r'}

it will print the address of these above 2 item using format specifier %c , here you are trying the to print the address %c instead of %u.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.