Home > Back-end >  What are the types of the elements of my 2D array? (new to C)
What are the types of the elements of my 2D array? (new to C)

Time:10-06

So I have the code below and I am wondering what the types of my elements are. I want them to be integers but I am not sure why when I assign a zero to a certain set of indices I have to use apostrophes. What would the type of my elements be? Output is a 10by10 array of zeros but I need the elements to be integers

#include <stdio.h>
#include <stdlib.h>

int main() {
    int accumulator[10][10];
    int i,j;

    for (i = 0; i < 5; i  ) {
        for (int j = 0; j < 5; j  ) {
            accumulator[i][j] = '0';
            printf("%c ", accumulator[i][j]);
        }
        printf("\n");
    }
    

    return 0;
}

CodePudding user response:

For arithmetic, use the int 0. For character strings, use the char '0'.

printf("Number %d\n", 0);
printf("Char %c\n", '0');

Output:

Number 0
Char 0

CodePudding user response:

In this statement

accumulator[i][j] = '0';

the integer character constant '0' has the type int and the value of the code of the character '0' For example in ASCII it is equal tp 48.

If you want to initialize the array with zeroes then you could either initialize the array in its declaration like

int accumulator[10][10] = { 0 };

or write

accumulator[i][j] = 0;

As for your question then the type of elements of the two-dimensional array is int[10]. That is elements of the array are one-dimensional arrays that in turn have the type of their elements int.

You can rewrite the declaration like

int ( accumulator[10] )[10];

Or you could introduce a typedef name like for example

typedef int T[10];

and then rewrite the declaration of the two-dimensional array like

T accumulator[10];

Now it is visually seen that the type of elements of the array is T that corresponds to the type int[10].

In this expression

accumulator[i][j]

the sibexpression

accumulator[i]

gives the i-th element of the array that as it was pointed out is a one-demensional array. Applying to the above expression the subscript operator you get an element of the element of the two-dimensional array

( accumulator[i] )[j]

that has the type int.

CodePudding user response:

why when I assign a zero to a certain set of indices I have to use apostrophes

Because you use wrong printf format specifier. If you want yo print integer use %d not %c.

printf("%d ", accumulator[i][j]);

  • Related