0

I am trying to use a pointer (*test) with a 2d char array (a[][]). But I can not seem to figure out what is the proper way to do it. I managed to get it working with an int array and int pointer, but the same solution did not work when I changed to char. I assume I was just lucky with ints, and did not really have a proper solution. I want to use pointer arithmetic to iterate as you can see in the code. My current output from this is gibberish.

char a[WIDTH][HEIGHT] = { {'a','b'},{'c','d'},{'e','f'} };

char *test = (char *)a[0][0];

int x,y;

for (x = 0; x < WIDTH; x++)
  {
    for (y = 0; y < HEIGHT; y++)
    {
      printf("%c", test);
      test = test + 1;
    }
    printf("\n");
  }
0

2 Answers 2

2
printf("%c", test);

You're trying to print the address of your character, not it's value. Dereference the pointer to access the value:

printf("%c", *test);

Moreover, you need to set the pointer to actually point to the address of the first element in your array. Currently, you're forcing the pointer to misuse it's value as an address:

char *test = (char *)a[0][0];

Change that to

char *test = &(a[0][0]);

In general, you should compile with all warnings enabled and treat every single one of them as error unless you're absolutely sure that it's not. You should also try to get by without any casts unless you're absolutely sure that you need one because casts may silence useful compiler warnings.

Finally I'd like to add that in my opinion this seems to be a way to iterate over an array that's just asking for future issues. If you want to express contiguous memory, use a single (1D) array. If you want grid like access, use a 2D array or even better, provide functions with expressive names.

Sign up to request clarification or add additional context in comments.

Comments

0

Two main problems are

  1. You are assigning the value of a[0][0] to test and casting to silence the compiler warning, you should assign the address which is simply a.

    char *test = (char *) a;
    

    Or

    char *test = (char *) a[0];
    

    This works because the array values are stored contigously in memory, but note that you should not rely on this if for example you create the 2 dimensional array dynamically, because that requires an array of pointers and hence the values will no longer be stored contigously.

  2. You are passing a pointer to printf() when you use the "%c" specifier, this specifier expects a char argument instead so it should be

    printf("%c", *test);
    

1 Comment

Thanks, and how would you I have to go about it if I had to create the array dynamically? In this exercise I have to stick to using the pointer.

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.