I have such function, which get 2 arrays as char arguments, i need to merge this strings. Sorry for easy question.
void Abc (char **a, char **b)
{
for (int i = 0; i < 200; i++)
{
a[i]="hello ";
}
for (int i = 0; i < 200; i++)
{
strcat(a[i], b[i]); //doesn't show mistake, but it's there
cout << b[i]<<'\n'; //ok
cout << a[i]<<'\n'; //ok
cout<<strlen(b[i])<<'\n'; //ok
cout<<strlen(a[i])<<'\n'; //ok
}
}
Why Strcat doesn't work here? What can i do to make this work?
The problem is in the following statement.
a[i]="hello ";
Instead of copying the string literal you assign its address.
Use instead
strcpy( a[i],"hello " );
First, every a[i]
is pointing to a string literal and modifying it invokes undefined behavior .
Second, when you're strcat(x, y)
you should make sure that x
has enough space to store merged x
and y
.
Therefore, x
should has allocated memory and to double check, you shoud use strncat
to avoid unintended overflow.
Here's the source of your problem:
for (int i = 0; i < 200; i++)
{
a[i]="hello ";
The compiler doesn't know your intent here, so every element of a[]
is assigned a pointer to the same string
a[0] == a[1] == a[2] == a[3] == a[4] == ... a[199]
Even if this worked, the problem is that all elements of a now point to a char array of size 7 {'h', 'e', 'l', 'l', 'o', 0}
. You can't stract
onto the end of them.
You need to ensure that each element of a[]
has a pointer to a unique storage space and that it is large enough to receive your strings. If your a[]
elements are already pointing somewhere valid, what you need to do is:
for (int i = 0; i < 200; i++)
{
strcpy(a[i], "hello ");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.