Reputation: 219
int main()
{
char *a1[10] = {"123","121"};
int i =0;
char *a=NULL;
for(i=0;i<2;i++)
{
a=strcat(a1[i],"0000");
printf("values %s",a);
}
}
Output of this code comes out to be this $ ./a.exe values 1230000 values 0000000
but it should be $ ./a.exe values 1230000 values 1210000
Please tell me where i am wrong
Upvotes: 2
Views: 99
Reputation: 41036
You want an array of array of char
, but char *a1[10]
is an array of pointers to char
(tipically placed in read-only segments / string literals), trying to modify a string literal usually leads to a segmentation fault.
Change
char *a1[10] = {"123","121"}; /* Array of string literals (read only) */
to
char a1[][10] = {"123","121"}; /* Array of array of char (read - write) */
Upvotes: 6
Reputation: 149085
The problem is not really the modification of string litterals. But the line
char *a1[10];
affects an array of 10 char *
and not a pointer to an array of char[10]
what I suppose OP was expecting (as noted in Jdamian comments).
To create an array of char[10]
, you must write :
char a1[][10] = {"123","121"};
That way, you create an array of 2 char[10]
initialized respectively to "123"
(in fact, { '1', '2, '3, '\0', '\0', '\0', '\0', '\0', '\0', '\0'}
as it is really a char[10]
) and "121";
That way you can safely strcat
"0000"
to a1[i]
because 3 (initial length) + 4 (added length) + 1 (terminating null) gives 8 <= 10.
But the really safe way would be :
a=strncat(a1[i],"0000", sizeof(a1[0]) - strlen(a1[i]) - 1);
Upvotes: 3