int被读为指针

时间:2015-11-15 12:59:45

标签: c pointers

我必须从用户那里取一个短语,然后将它打印成倒三角形,中间有空格。我的程序接受短语,将其存储到inputBuffer(char数组)中,然后创建一个大小为string的新数组。它用空格填充前半部分,后半部分用字符串填充。我想从新数组strLength时间打印出strLength char,只需将strLength的范围每次向左移动到(strLength * 2-1)1。这样可以确保在第一次迭代中只打印整个字符串,第二次打开一个空格,最后一个字符不打印,如下所示。
目前我收到一个错误,即使通过strLength是一个int变量,当我用它来创建新数组时,它显然不是一个常量值。

int main(void) {

char inputBuffer[256];
char *pointer = inputBuffer;
char *temp = pointer;
int strLength = 0;

printf("enter your word: ");
scanf("%s", pointer);

//Calculate string length
while (*temp++) strLength++;

//Create an array double the size, first half for white spaces, and second half for the phrase.
char inputString[strLength * 2];
// ERROR: above expression inside the index must be a constant value.
int i, j;

//First half of array is number of spaces == number of char in phrase

for (i = 0; i < strLength; i++) {
    inputString[i] = ' ';
}

//Reinitialize temp to use instead of pointer & put the string in the second half of inputString[]

temp = pointer;
for (j = 0; j < strLength; j++) {
    inputString[i++] = *temp++;
}

//Just print the strLength indexes of inputStrng[] starting from half to end, and keep shifting the range by 1 position to the left.

for (i = strLength; i < (strLength * 2); i--) {
    for (j = 0; j < strLength; j++) {
        putchar(inputString[i + j]);
        putchar(' ');
    }
    putchar('\n');
}

return 0;
}

1 个答案:

答案 0 :(得分:0)

用于创建inputString的索引变量实际上不是常量,它是一个变量..

如果要创建可变大小的数组,则必须使用malloc ..您必须使用malloc语句替换行char inputString[strLength * 2]; ..

See this answer

所以..这样的事情:

char * inputString = malloc( sizeof(char) * ( (strLength * 2) + 1 ) );