C-使基于数组的程序起作用,没有元素



练习它以取一系列字符串,并使用指针将它们串联成新字符串。我通过硬编码每个字符串阵列索引的值来使其起作用,但是如果数组没有元素,我不知道如何使其起作用。我认为我需要完全重组我的代码...

#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] == '') {
            break;
        }
        else {
            firstStringCount++;
        }
    }
    //count length of second element
    for (int i = 0; i < 1000; i++) {
        if (secondString[i] == '') {
            break;
        }
        else {
            secondStringCount++;
        }
    }
    //count length of third element
    for (int i = 0; i < 1000; i++) {
        if (thirdString[i] == '') {
            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] = '';

    printf("%sn", concatenatedString);
    printf("%in", firstStringCount);
    printf("%in", secondStringCount);
    printf("%in", thirdStringCount);
    return 0;
}

当您有空字符串时,您的程序将起作用。这与没有数组元素不同,因为每个数字末端仍然必须有一个终结器,例如用

创建的
newArray[0] = "";

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

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

您现在有

的终结者的空间
concatenatedString[firstStringCount + secondStringCount + thirdStringCount] = '';

相关内容

  • 没有找到相关文章

最新更新