Sagar Varma Sagar Varma - 24 days ago 6
C Question

Accessing Three Dimensional Character Array

char t[] = {'a','b','$'};
char nt[] = {'S','A'};
char table[2][3][2] = { {"AA","AA",""}, {"aA","b",""} };

void main(){

printf("%s",table[0][0]);
}


Output:


AAAA


The output should be
AA
, can somebody help me out,can't figure out the problem.

Answer

Your array doesn't have space for null terminator. The right most dimension of table must be at least 3 in order to use the elements as C-strings. You are now accessing out-of-bounds of the array (when you print it using %s in the printf()) which is undefined behaviour.

char table[2][3][3] = ...

Similarly adjust the length if you are going to have string literals with greater lengths.

Btw, void main() is not a standard signature for main(). Use int main(void) or similar.