练习它获取一个字符串数组,并使用指针将它们连接在一个新字符串中。我通过对每个字符串数组索引处的值进行硬编码来使其工作,但是如果数组没有元素,我无法弄清楚如何使它工作。我想我需要完全重构我的代码...
#include <stdio.h>
#include <stdlib.h>
int main(int argc, const char * argv[]) {
char *newArray[3];
//original code didn't have newArray as a pointer, and had the following:
//char *firstString = &newArray[0]; This was pointing to the value at the address of newArray[0] which was null at this point in time
//firstString = "Knicks"; This was reassigning the value of firstString to "Knicks" instead of pointing to the value located at the proper index address.
//this code correctly assigns values to each index of the array (which itself is just a pointer that is pointing to these values
newArray[0] = "Knicks";
newArray[1] = "Warriors";
newArray[2] = "Bulls";
//this code correctly assigns pointers that point to the index values of the array, which are all stated above.
char *firstString = newArray[0];
char *secondString = newArray[1];
char *thirdString = newArray[2];
int firstStringCount = 0;
int secondStringCount = 0;
int thirdStringCount = 0;
//count length of first element
for (int i = 0; i < 1000; i++) {
if (firstString[i] == '\0') {
break;
}
else {
firstStringCount++;
}
}
//count length of second element
for (int i = 0; i < 1000; i++) {
if (secondString[i] == '\0') {
break;
}
else {
secondStringCount++;
}
}
//count length of third element
for (int i = 0; i < 1000; i++) {
if (thirdString[i] == '\0') {
break;
}
else {
thirdStringCount++;
}
}
//int len = firstStringCount + secondStringCount + thirdStringCount;
char *concatenatedString = malloc(firstStringCount + secondStringCount + thirdStringCount);
for (int i = 0; i < firstStringCount; i++) {
concatenatedString[i] = firstString[i];
}
for (int i = 0; i < secondStringCount; i++) {
concatenatedString[i+firstStringCount] = secondString[i];
}
for (int i = 0; i < thirdStringCount; i++) {
concatenatedString[i+firstStringCount+secondStringCount] = thirdString[i];
}
//add in null value
concatenatedString[firstStringCount + secondStringCount + thirdStringCount] = '\0';
printf("%s\n", concatenatedString);
printf("%i\n", firstStringCount);
printf("%i\n", secondStringCount);
printf("%i\n", thirdStringCount);
return 0;
}
答案 0 :(得分:2)
当您有空字符串时,您的程序将起作用。这与没有数组元素不同,因为每个数组元素中仍然必须有一个\0
终结符,例如将使用
newArray[0] = "";
但是你没有为目标的字符串终止符分配足够的内存。使用1 +
char *concatenatedString = malloc(1 + firstStringCount + secondStringCount +
thirdStringCount);
你现在有了
终结者的空间concatenatedString[firstStringCount + secondStringCount + thirdStringCount] = '\0';