C

时间:2015-12-01 09:06:26

标签: c

我在初始化动态大小变量时遇到了有趣的情况。

例如:

// 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();

在这种情况下肯定不会工作,因为编译器不能将一些固定大小的内存分配给堆,这是对的吗?

但在这种情况下,它运作正常:

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

为什么它在第一种情况下不起作用而在第二种情况下起作用?可能strcpy使用malloc还是其他什么?

3 个答案:

答案 0 :(得分:12)

  

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

在同一个表达式中调用两次getInput()函数没有任何意义。特别是,您不会使用=运算符复制字符串,而是复制strcpy()。此外,您需要为null终止符分配空间。

假设这些是本地变量(它们应该是),你应该做的是:

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

但在这种情况下,它运作正常:

     

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

不,它不能正常工作!你所做的就是声明一个大小为1的静态数组(空终止符的大小),然后将长度较长的数据复制到该数组中。这会导致数组超出界限错误,这是未定义的行为,任何事情都可能发生。不幸的是,它导致你的程序似乎工作正常,而它实际上有一个潜在的严重错误。

答案 1 :(得分:1)

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

您正在将char vector[strlen(getInput())] =期望的char数组初始化与getInput()返回的数组指针的赋值混合。

可能的解决方案

您可以使用值

初始化数组
char vector[strlen(getInput())] = { 'a', 'b', .. 'z' };

或者获取getInput

返回的数组指针
const char * vector = getInput();

或者将getInput返回的数组复制到向量数组

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

答案 2 :(得分:-1)

似乎函数 getInput 返回一个字符指针,因此您无法将结果分配给数组。

也在
char path[] = "";

path 的长度只有一个字符(空字符),因此只有输入为空字符串时,才能将输入复制到此变量。

你可能想要这样的东西:

#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;
}
相关问题