简体   繁体   English

C中的动态大小数组

[英]A dynamic size array in C

I have encountered with interesting situation when initializing dynamic size variables. 初始化动态大小变量时遇到了有趣的情况。

For example: 例如:

// getInput() is some magic method to retrieve input with dynamic length string
// some times it can be 10, some times 99 and so on
char vector[strlen(getInput())] = getInput();

In this case definitely wont work since compiler can't allocate some fixed size memory to heap, that's right? 在这种情况下肯定不会工作,因为编译器不能分配一些固定大小的内存到堆,这是正确的?

But in this case, it works fine: 但在这种情况下,它工作正常:

char path[] = "";
strcpy(path, getInput());

Why it doesn't work in first case and works in second? 为什么它在第一种情况下不起作用而在第二种情况下工作? Is maybe strcpy uses malloc or something? 也许strcpy使用malloc或者什么?

char vector[strlen(getInput())] = getInput();

Calling the getInput() function twice in the same expression doesn't make any sense. 在同一个表达式中调用两次getInput()函数没有任何意义。 In particular, you don't copy strings with the = operator but with strcpy() . 特别是,您不使用=运算符复制字符串,而是使用strcpy()复制字符串。 Also, you need to allocate space for the null terminator. 此外,您需要为null终止符分配空间。

Assuming these are local variables (they should be), what you should do instead is this: 假设这些是局部变量(它们应该是),你应该做的是:

int main (void)
{
  const char* input = getInput();
  char vector[strlen(input) + 1];
  strcpy(vector, input);
  ...
}

But in this case, it works fine: 但在这种情况下,它工作正常:

char path[] = "";
strcpy(path, getInput());

No, it doesn't work fine! 不,它不能正常工作! All you did was do declare a static array of size 1 (size of the null terminator), then you copy data of longer length into that array. 你所做的就是声明一个大小为1的静态数组(空终止符的大小),然后将长度较长的数据复制到该数组中。 This causes an array out of bounds bug which is undefined behavior , anything can happen. 这会导致数组超出界限的bug,这是未定义的行为 ,任何事情都可能发生。 Unfortunately, it caused your program to seem to work ok, while it actually has a latent severe bug. 不幸的是,它导致你的程序似乎工作正常,而它实际上有一个潜在的严重错误。

char vector[strlen(getInput())] = getInput();

You are mixing a char array initialization expected by char vector[strlen(getInput())] = with the assignment of a array pointer returned by getInput() . 您正在混合char vector[strlen(getInput())] =期望的char数组初始化,以及getInput()返回的数组指针的赋值。

Possible Solutions 可能的解决方案

You can either initialize the array with values 您可以使用值初始化数组

char vector[strlen(getInput())] = { 'a', 'b', .. 'z' };

Or obtain the array pointer returned by getInput 或者获取getInput返回的数组指针

const char * vector = getInput();

Or copy the array returned by getInput into vector array 或者将getInput返回的数组复制到向量数组中

const char * input = getInput();
const size_t size = strlen(input);
char vector [size+1] = { 0 };
memset(vector , '\0', sizeof(vector));
strcpy(vector,input);

It seems like the function getInput returns a character pointer, so you cannot assign the result to an array. 似乎函数getInput返回一个字符指针,因此您无法将结果分配给数组。 Also in 也在

char path[] = "";

the length of path is only one character (the null character), so copying the input to this variable is only valid if the input is the empty string. path的长度只有一个字符(空字符),因此只有输入为空字符串时,才能将输入复制到此变量。

You probably want something like this: 你可能想要这样的东西:

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

#define NEW_ARRAY(ptr, n) \
    { \
        (ptr) = malloc((n) * sizeof (ptr)[0]); \
        if ((ptr) == NULL) { \
            fprintf(stderr, "error: Memory exhausted\n"); \
            exit(EXIT_FAILURE); \
        } \
    }

const char *getInput(void);

int main(void)
{
    const char *input;
    char *inputCopy;
    int inputLength;

    input = getInput();
    inputLength = strlen(input);
    NEW_ARRAY(inputCopy, inputLength + 1);
    strcpy(inputCopy, input);

    return 0;
}

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

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