在C编程中声明没有大小的数组

时间:2018-09-23 17:26:54

标签: c arrays twos-complement

我正在编写一个程序,假设输入以无符号幅度和二进制补码形式给出,则它将给定的位字符串(最多32位)转换为十进制。我一次从用户读取每个字符一个字符,并尝试将其存储到数组中,但是数组没有所需的大小。有没有一种方法可以让数组在不知道数组大小的情况下通过循环?我还试图找出一种不使用pow和乘法功能的方法。我在下面发布我的代码,如果您有任何想法请

#include "stdio.h"
#include "math.h"

#define MAX_BITS 32
#define ENTER '\n'
#define NUMBER_TWO 2

int main()
{
        int unsignedMag;
        int twosComp;
        int negation[n];
        int bitStore[n];
        char enter;

        //Input from the User
        printf("Enter up to 32 bits (hit 'enter' to terminate early): ");

        //Reads the first bit as a character
        char bit = getchar();
        while (getchar != enter) {
                bit = bit - '0';
                scanf("%c", &bitStore[bit]);
                getchar();
        }

        //Terminates if user hits enter
        if (bit == enter) {
                return 0;
        }

        //Continue through code
        else {
                //Loop to calculate unsigned magnitude
                for (int i = 0; i < bitStore[i]; i++) {
                        unsignedMag = unsignedMag + (bitStore[i] * pow(NUMBER_TWO, i));
                }

                //Loop to calculate complete negation
                for (int j = 0; j < bitStore; j++) {
                        negation[j] = ~bitStore[j]
                }
                negation = negation + 1;
                for (int l = 0; l < negation; l++) {
                        twosComp = twosComp + (negation[l] * pow(NUMBER_TWO, l));
                }


        }
        return 0;

}

1 个答案:

答案 0 :(得分:2)

  

“有没有一种方法可以让数组在不知道数组大小的情况下通过循环?”

不。数组大小固定在声明数组且大小已知的位置: @Observer

size_t size = sizeof bitStore/sizeof bitStore[0];

相反,由于代码具有“给定的位字符串(最多32位)”,因此将数组定义为大小为32(或33为 string )。
跟踪分配了多少阵列。

//int bitStore[n];
int bitStore[MAX_BITS];
int count = 0;

// char bit = getchar();
int bit = getchar(); // Use `int` to account for potentially 257 different values

//while (getchar != enter) {
while (count < MAX_BITS && (bit == '0' || bit == '1')) {
    bit = bit - '0';

    // Do not read again, instead save result. 
    //scanf("%c", &bitStore[bit]);  
    bitStore[count++] = bit;

    // getchar();
    bit = getchar();
}

  

不使用pow和乘法功能。

通过移位简单地相加或乘以2。尚不清楚为什么OP的目标是不使用“乘法”。我几乎没有理由禁止*。当底层乘法非常昂贵时,*2很难优化,一个好的编译器将发出有效的代码。

    // int unsignedMag;
    unsigned unsignedMag = 0; // initialize

    // for (int i = 0; i < bitStore[i]; i++) {
    for (int i = 0; i < count; i++) {
      // preferred code, yet OP wants to avoid * for unclear reasons 
      // unsignedMag = unsignedMag*2 + bitStore[i];
      unsignedMag = unsignedMag + unsignedMag + bitStore[i];
    }
出于多种原因,

pow()可以避免。最重要的是,对整数问题使用double数学会遇到宽整数的精度问题。


  

将给定的位字符串(最多32位)转换为十进制

请注意,此任务不需要bitStore[] array 。只需在读取数据时形成unsignedMag即可。