调整C中的数组 [英] Resizing an array in C

查看:111
本文介绍了调整C中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我分配这样一个数组:

Say I assigned an array like so:

char* array[]={"This"};

再后来我想,这样它存储分配[]数组新值这和那,在那里,我可以改变数组的大小,使其能够容纳值的新号码的方法?

And then later I wanted to assign array[ ] a new value so that it stores "This" and "That," is there a way that I could change the size of array so that it could hold a new number of values?

推荐答案

没有,你不能改变一个数组的大小。你可以使用的char * ,而不是一个动态分配的列表和的realloc()的要求:

No, you can't change the size of an array. You could use a dynamically allocated list of char* instead and realloc() as required:

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

int main()
{
    char** array = malloc(1 * sizeof(*array));

    if (array)
    {
        array[0] = "This";

        printf("%s\n------\n", array[0]);

        char** tmp = realloc(array, 2 * sizeof(*array));
        if (tmp)
        {
            array = tmp;
            array[1] = "That";

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

        free(array);
    }
    return 0;
}

请参阅在线演示: https://ideone.com/ng00k

这篇关于调整C中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆