I am trying to use the following code to append a right parenthesis to the end of a string took from the user
int main( void )
{
char charArray[ 20 ];
fgets( charArray, 20, stdin );
charArray[ sizeof( charArray ) / sizeof( charArray[ 0 ] ) ] = ')';
printf( "%s", charArray );
}
but if I enter: 4+5 the output is just: 4+5 rather then: 4+5)
I tried even the following variant, just in case
int main( void )
{
char charArray[ 20 ];
int n;
fgets( charArray, 20, stdin );
n = sizeof( charArray ) / sizeof( charArray[ 0 ] );
charArray[ n ] = ')';
printf( "%s", charArray );
}
but it doesn't work. So I obviated the need for a sizeof by doing
int main( void )
{
char charArray[ 20 ];
int i = 0;
do{
scanf( "%c", &charArray[ i ] );
++i;
} while( charArray[ i - 1 ] != '\n' );
charArray[ i - 1 ] = ')';
printf( "%s", charArray );
}
However I could need sizeof in the future so I would like to know what I am doing wrong. Also the use of fgets and sizeof seems more direct and concise than that of scanf and do while with the mysterious [ i - 1 ] subscript. Just enlighten me about the sizeof approach please: what's wrong with my piece of code?
charArray[ sizeof( charArray ) / sizeof( charArray[ 0 ] ) ] = ')';
is by definition writing out of bounds of the array. – Flotillastrlen
? – Vasques