简体   繁体   English

C改变结构内数组的大小

[英]C changing size of the array inside struct

#include <stdio.h>
#include <stdlib.h>

#define TRUE 1

struct Cases
    {
        char name[3];
        int cases;
    };



int main()
{
    int n=5;
    struct Cases Real;
    Real.name[0] = 'a';
    Real.name[1] = 'b';
    Real.name[2] = 'c';
    printf("Size before: %d \n", sizeof Real.name);
    Real.name = (char *)malloc(5 * sizeof(char));
    printf("Size after: %d \n", sizeof Real.name);


    return 0;
}

Hi, i am trying to change the size of the array inside structure, but it gives error.嗨,我正在尝试更改结构内部数组的大小,但它给出了错误。 I tried to do it first empty array but that didn't work out aswell.我试图先做空数组,但这也没有奏效。 Any help ?有什么帮助吗?

Hi, i am trying to change the size of the array inside structure嗨,我正在尝试更改结构内部数组的大小

You cannot change the size of an array, it's a constant.你不能改变数组的大小,它是一个常量。 If you try to assign to a variable of any array type, you'll see error, as an array is not a modifiable lvalue.如果您尝试分配给任何数组类型的变量,您将看到错误,因为数组不是可修改的左值。

As an alternative: You can define a pointer, and allocate memory dynamically using the allocator functions (as you tried).作为替代方案:您可以定义一个指针,并使用分配器函数动态分配内存(如您所尝试)。

This is impossible without the use of pointers , an example for you to be able to do this with pointers :如果不使用pointers ,这是不可能的,这是一个可以使用pointers执行此操作的示例:

#include <stdio.h>

int main ()
{
     char **real = malloc (3 * sizeof (* array));
     real[0] = "a";
     real[1] = "b";
     real[2] = "c";

     printf ("% My array in position 0 n", real[0]);

     char ** tmp = realloc (real, 5 * sizeof (* array));
     real = tmp;
     real[1] = "G";

     printf ("% s \ n", real [0]);
     printf ("% s \ n", real [1]);
         

     free (array);
     return 0;
}

You could do something close to that with a flexible array :你可以用一个灵活的数组做一些接近的事情:

struct Cases
{
        int cases;
        char name[]; //Must be the last element in the struct   
};

int main()
{
    struct Cases * real = (struct Cases *)malloc(sizeof(struct Cases) + 3 * sizeof(char));
    real->length  = 3;
    real->name[0] = 'a';
    real->name[1] = 'b';
    real->name[2] = 'c';
    printf("%d\n", real->length);           //=> 3
    
    real = (struct Cases *)realloc(real, sizeof(struct Cases) + 5 * sizeof(char));
    real->length  = 5;
    real->name[3] = 'd';
    real->name[4] = 'e';
    printf("%d\n", real->length);           //=> 5

    printf("%ld\n", sizeof(real));          //=> 8 (the size of the pointer)
    printf("%ld\n", sizeof(struct Cases));  //=> 8 (the size of the structure without the array)
    
    free(real);
    return 0;
}

However you must memorize the size by yourself (I added a field to the structure for that purpose).但是,您必须自己记住大小(为此我在结构中添加了一个字段)。

As you've defined it, name is an array of three elements, inside a struct .正如您所定义的, name是一个包含三个元素的数组,位于struct As such, its size cannot be changed.因此,它的大小不能改变。 If you want to be able to change the size dynamically, you can declare it as a char pointer, then allocate the storage dynamically (and free it when done).如果您希望能够动态更改大小,您可以将其声明为一个char指针,然后动态分配存储空间(并在完成后释放它)。

Here's an example of what this might look like:下面是一个示例:


#include <stdio.h>
#include <stdlib.h>

struct Cases
{
    char *name;
    int cases;
};

int main(void)
{
    struct Cases Real;

    Real.name = malloc(3 * sizeof(char));
    if (Real.name == NULL) {
        fprintf(stderr, "Malloc failed.\n");
        exit(1);
    }

    Real.name[0] = 'a';
    Real.name[1] = 'b';
    Real.name[2] = 'c';

    Real.name = realloc(Real.name, 5 * sizeof(char));
    if (Real.name == NULL) {
        fprintf(stderr, "Realloc failed.\n");
        exit(1);
    }

    Real.name[3] = 'd';
    Real.name[4] = 'e';

    free(Real.name);

    return 0;
}

In this example, name is now a char pointer, which is first set with malloc to be able to hold 3 elements.在这个例子中, name现在是一个char指针,它首先用malloc设置为能够容纳 3 个元素。 It is later grown with realloc to be able to hold 5 elements.后来用realloc增长到能够容纳 5 个元素。 Finally, it is freed by calling free .最后,它通过调用free被释放。

Under normal circumstances, this example doesn't print anything out.在正常情况下,此示例不会打印任何内容。 It will print an error message if either malloc or realloc fails.如果mallocrealloc失败,它将打印错误消息。 You should always check the result of malloc or realloc to see if it's NULL before attempting to use it.在尝试使用之前,您应该始终检查mallocrealloc的结果以查看它是否为NULL

Note that these arrays do not have a terminating null character in the example (although you could certainly add one if desired, provided you've allocated space for it).请注意,这些数组在示例中没有终止空字符(尽管如果需要,您当然可以添加一个,前提是您已为其分配空间)。 Also note that sizeof is no longer useful when used on name , since name is now a pointer.还要注意sizeofname上使用时不再有用,因为name现在是一个指针。 You need to keep track of the size yourself.您需要自己跟踪尺寸。 If needed, you could add a size field to Cases , setting it to the current size.如果需要,您可以向Cases添加一个size字段,将其设置为当前大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM