Рейтинг:
26
Richard MacCutchan
Как говорит OriginalGriff, вам нужно правильно завершить свою строку таким образом:
For (k=len1;k <len1+len2;k++)
{
s1 [k] = s2 [i];
++i;
}
s1[k] = '\0'; // add the terminating null to the end of the array
Вы также должны проверить, что len1 + len2 меньше 20.
Member 13922884
Спасибо. Это сработало. Но у меня есть сомнения.
Длина двух струн, которые я беру, равна 4 и 7. Так что Итого получается 11. Тогда почему он принимает только 4 мусорных значения? Если он не отображает значения мусора до 20 подсчета, то есть 9.
Richard MacCutchan
When you allocate a variable (whether a single item or array) the compiler makes a note of its relative address (starting at zero) and its length. The name of the item is the first (or only) element that is allocated. The next variable that you create will be given an address following the previous one. But these addresses are known only to the compiler in order to generate the correct address references in your code. If you decide to write 100 items in an array that was defined as holding only 20 then it is your problem, the compiler cannot prevent you from doing that. Similarly if you add fewer items than the maximum, then neither the compiler nor the run time libraries will know that. So when you try to print a character array that does not have a terminating null character, the library function will continue to display characters until it finds a null. So if a character array of size 20 contain 11 valid characters but does not have a null at position 11 (0-10 being valid), then it will continue to try and print until it finds a null. That could be at offset 15, or even offset 50,000.
Richard MacCutchan
Это происходит потому, что функция печати будет продолжать печатать символы, пока не найдет нулевой символ. Поскольку вы добавили только 11 символов в массив, то все, что было в оставшейся части памяти до этого, будет напечатано. Если нулевой символ находится на четыре символа выше ваших данных, то это то, где он остановится. Если он не будет найден до 4000 символов дальше, то у вас будет хорошая куча мусора, напечатанного. Когда вы выделяете массив из 20 символов, вы должны правильно управлять этим пространством. Компилятор и библиотеки времени выполнения не управляют этим за вас.
Member 13922884
Ладно, понял. Большое спасибо.
Рейтинг:
0
OriginalGriff
И тому есть немало причин.
The first one is that you are trying to append two strings of equal length - 20 characters each - into the space allocated for one of them. If both len1 and len2 values add up to less than 20, you don't have a problem. But if they exceed that, then you are "running off the end" of one array or the other, and that's a problem because you don't know what memory you are using, so you don't know what you are overwriting. The compiler isn't going to tell you, and there is no standard that will define that because it's a bad, bad idea to do it in the first place! Define an output string area that is big enough to hold both strings, plus an extra character.
Этот дополнительный символ приводит нас ко второй причине: строки в C - это просто массив символов, заканчивающийся символом, содержащим нулевое значение - '\0'
Поскольку вы не копируете и не добавляете '\0' в конец вывода, когда вы печатаете строку, она не прекращает печатать символы, пока не достигнет ячейки памяти, которая просто случайно содержит null. Таким образом, вы получаете случайное число случайных символов, напечатанных после ваших ожидаемых данных.
Member 13922884
Это был максимальный предел, который я дал. Я не превышаю предел 20.
Рейтинг:
0
CPallini
Попробуй
#include <stdio.h>
// merges strings 's1', 's2' into bufer 'buf', having size 'bufsize'
// returns 0 on success.
int merge( const char * s1, const char * s2, char * buf, size_t bufsize)
{
const char * sa[2] = {s1, s2 };
size_t i = 0;
size_t k = 0;
for ( i = 0; i<2; ++i)
{
const char *p = sa[i];
while ( *p )
{
if ( k == bufsize) return -1;
buf[k] = *p;
++k;
++p;
}
}
if ( k == bufsize) return -1;
buf[k] = '\0';
return 0;
}
// usage example
int main()
{
const char * s1 = "foo";
const char * s2 = "bar";
char m[20];
int rc = merge(s1, s2, m, sizeof(m));
if ( rc )
printf("unable to merge\n");
else
printf("merged string '%s'\n", m);
return 0;
}
Member 13922884
Спасибо за ваш ответ. Но я всего лишь новичок и до сих пор не добрался до указателя.
Я хотел узнать ошибку в своем коде.