gpt4 book ai didi

c - 使基于数组的程序在没有元素的情况下工作

转载 作者:太空宇宙 更新时间:2023-11-04 08:26:40 24 4
gpt4 key购买 nike

练习它获取一个字符串数组,并使用指针将它们连接成一个新字符串。我通过对每个字符串数组索引处的值进行硬编码来使其工作,但如果数组没有元素,我无法弄清楚如何使其工作。我想我需要完全重构我的代码...

#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 终止符,例如用

创建的
newArray[0] = "";

但是您没有为目标的字符串终止符分配足够的内存。通过使用 1 +

char *concatenatedString = malloc(1 + firstStringCount + secondStringCount +
thirdStringCount);

你现在有空间给终结者了

concatenatedString[firstStringCount + secondStringCount + thirdStringCount] = '\0';

关于c - 使基于数组的程序在没有元素的情况下工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30197493/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com