Reputation: 13
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.
Upvotes: 0
Views: 217
Reputation: 121347
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.
Upvotes: 1
Reputation: 310920
In fact your declaration of the array table is equivalent to the following declaration
char table[2][3][2] = { { { 'A', 'A' }, , { 'A', 'A' },, { '\0', '\0' } },
{ { 'A', 'A' }, { 'b', '\0' }, { '\0', '\0' } } };
As you can see not all elements of sub arrays table[i][j] where i and j some indices contain strings. Thus to output an element of such sub arrays you should specify exactly how many characters you are going to output. You can do that the following way
printf( "%*.*s\n", 2, 2, table[0][0] );
Here is a more complete example
char table[2][3][2] = { {"AA","AA",""}, {"aA","b",""} };
for ( size_t i = 0; i < 2; i++ )
{
for ( size_t j = 0; j < 3; j++ ) printf( "%*.*s ", 2, 2, table[i][j] );
printf( "\n" );
}
The program output is
4
AA AA
aA b
However it would be much better if the array contained strings that is that there was rooms for the terminating zeroes.
For example C++ does not allow such definition of character arrays when there is no room for the terminating zero when an array is initialized by a string literal. The compiler will issue an array.
Thus declare the array the following way
char table[2][3][3] = { {"AA","AA",""}, {"aA","b",""} };
^^^^^
Take into account that the function main without parameters shall be defined in C like
int main( void )
Upvotes: 0