In this declaration
char arr[MAX_ARR_LENGTH][30] = {"Tom", "and", "Jerry" };
you declared an array of MAX_ARR_LENGTH
elements of the type char[30]
and initialized it with three string literals.
I suppose that the value of MAX_ARR_LENGTH
is greater than 3
.
In this case all other elements of the array that were not explicitly initialized by the string literals are implicitly initialized by zero. It means that all other elements are initialized as empty strings.
So to append a new string to the array you can write for example
#include <string.h>
//...
size_t i = 0;
while ( i < MAX_ARR_LENGTH && arr[i][0] != '\0' ) ++i;
if ( i < MAX_ARR_LENGTH ) strcpy( arr[i], "Jack" );
Here is a demonstration program.
#include <stdio.h>
#include <string.h>
#define MAX_ARR_LENGTH 10
int main( void )
{
char arr[MAX_ARR_LENGTH][30] = { "Tom", "and", "Jerry" };
for (size_t i = 0; i < MAX_ARR_LENGTH && arr[i][0] != '\0'; i++)
{
printf( "%s ", arr[i] );
}
putchar( '\n' );
size_t i = 0;
while (i < MAX_ARR_LENGTH && arr[i][0] != '\0') ++i;
if (i < MAX_ARR_LENGTH) strcpy( arr[i], "Jack" );
for (size_t i = 0; i < MAX_ARR_LENGTH && arr[i][0] != '\0'; i++)
{
printf( "%s ", arr[i] );
}
putchar( '\n' );
}
The program output is
Tom and Jerry
Tom and Jerry Jack
On the other hand, it will be better to track the number of actually initialized elements from the very beginning.
Here is another demonstration program.
#include <stdio.h>
#include <string.h>
#define MAX_ARR_LENGTH 10
int main( void )
{
char arr[MAX_ARR_LENGTH][30] = { "Tom", "and", "Jerry" };
size_t n = 0;
while (n < MAX_ARR_LENGTH && arr[n][0] != '\0') ++n;
for (size_t i = 0; i < n; i++)
{
printf( "%s ", arr[i] );
}
putchar( '\n' );
if (n < MAX_ARR_LENGTH) strcpy( arr[n], "Jack" );
++n;
for (size_t i = 0; i < n; i++)
{
printf( "%s ", arr[i] );
}
putchar( '\n' );
}
The program output is the same as shown above
Tom and Jerry
Tom and Jerry Jack