在C中的数组末尾添加了不需要的字符

问题描述 投票:-1回答:3

我想键入一系列字符并使用临时数组保存它们。之后,我想创建具有一定大小的实际数组,其中包含临时数组的值。这是代码:

#include <stdio.h>

int main()
{
    char c;
    char temp[100];
    char array[24];
    int i;
    char *ptrtemp = temp;


    // create a temporary array with getchar function
    while(1) {

        c = getchar();

        if(c == '\n')
            break;

        *ptrtemp = c;
        i++;
        ptrtemp++;

    }

    // type wrong in case of wrong size
    if(i != 24) {

        printf("Data is wrong");
        exit(0);
    }

    char *ptrarray = array;
    char *ptrtemp2 = temp;

    // create the actual array
    for(i=0;i<24;i++) {

        *ptrarray = *ptrtemp2;
        if(i == 23)
            break;
        ptrarray++;
        ptrtemp2++;
    }

    //printing the actual array
    printf("\n%s\n", array);
}

但是,我在实际序列之后得到了有趣的元素。阵列的大小表示为24,但第25,26,27等元素也被打印出来。

Here is what I get

每次尝试,我都会看到不同的额外字符。任何人都可以解释这里发生了什么?

c arrays pointers
3个回答
1
投票

你做的事太复杂了。

首先,如已经表示的那样,我没有初始化。其次,不要为数组中的终止0留出空间。最后,您可以直接轻松地写入数组:

char array[24 + 1]; // need space for the terminating 0 character

for(int i = 0; i < 24; ++i)
{
    // write to array directly:
    array[i] = getchar();
    if(array[i] == '\n')
    {
        printf("Data is wrong");
        return 0;
    }
}

array[24] = 0; // this is important if using %s!
printf("\n%s\n", array);

实际上,你有另一种选择,因为你知道你总是想要打印24个字符:

char array[24]; // skipping(!) space for the terminating 0 character

for(int i = 0; i < 24; ++i)
{
    // just as above
}

// NOT now (would be UB, as array is too short):
// array[24] = 0;

// but now need to give precision to tell how many bytes to write
// (maximally; if a terminating 0 would be encountered before,
// printf would stop there)
printf("\n%.24s\n", array);

0
投票

我修改了以下内容:

  1. 在开始时将i初始化为0。
  2. memset(temp,0,sizeof(temp));
  3. 添加以下内容以确保它不会跨越数组边界。

if (i == 99)
{
    break;
}
  1. 同样为数组变量添加以下内容。

memset(array, 0, sizeof(array));
  1. 以下检查是在for循环开始时完成的,以确保它不会写入数组的第24个元素。

if(i == 23)
     break;
#include <stdio.h>

int main()
{
    char c;
    char temp[100];
    char array[24];
    int i = 0; //Should be initialized to 0
    char *ptrtemp = temp;

    memset(temp, 0, sizeof(temp));

    // create a temporary array with getchar function
    while(1) {

        c = getchar();

        if(c == '\n')
            break;

        *ptrtemp = c;
        i++;
        ptrtemp++;

        if (i == 99)
        {
           break;
        }

    }

    char *ptrarray = array;
    char *ptrtemp2 = temp;

    memset(array, 0, sizeof(array));

    // create the actual array
    for(i=0;i<24;i++) {
        if(i == 23)
            break;
        *ptrarray = *ptrtemp2;
        ptrarray++;
        ptrtemp2++;
    }

    //printing the actual array
    printf("\n%s\n", array);
}

如果您遇到任何问题,请告诉我。


-1
投票

两个问题:

  1. 您在代码中使用的是未初始化的。 (我不认为你看到的问题是因为那个)
  2. 所有C字符串都需要'\ 0'终止。为了确保是这种情况,您可以随时执行以下操作: memset(array,0,sizeof(array));
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.