【问题标题】:C - using dynamic arraysC - 使用动态数组
【发布时间】:2012-01-03 14:56:03
【问题描述】:

我在 C 中有一个问题。这是问题:

开发一个将两个整数数组相加的 C 函数加法器。 ADDER应该只有两个参数,就是要相加的两个数组。第二个数组参数将保存退出时数组的总和。两个参数都应该通过引用传递。

编写一个 C 程序以调用 ADDER (A, A) 来测试 ADDER 函数,其中 A 是要添加到自身的数组。数组 A 可以是具有任何值的任何大小。编写、编译和执行程序。

解释程序的结果。


到目前为止,我已经以这种方式解决了它,并且效果很好:

#include <stdio.h>

// using namespace std;

const int SIZE = 5;

/* Adds two arrays and saves the result in b
 * Assumes that b is larger than or equal to a in size
 */

void ADDER(int (&a)[SIZE], int (&b)[SIZE]) {
    int aSize, bSize, i; /* variable declaration */
    /* find out the sizes first */
    aSize = sizeof (a) / sizeof (int);
    bSize = sizeof (b) / sizeof (int);
    /* add the values into b now */
    for (i = 0; i < aSize; i++) {
    b[i] = b[i] + a[i];
    }
    /* we have the sum at the end in b[] */
}

/* Test program for ADDER */

int main() {
int i; /* variable declaration */
int a[] = {1, 2, 3, 4, 5}; /* the first array */

/* add them now */
ADDER(a, a);
/* print results */
printf("\nThe sum of the two arrays is: ");
for (i = 0; i < SIZE; i++) {
    printf("%d ", a[i]); /* print each element */
}
return 0;
}

问题是,我必须使用动态数组并在程序中使用 malloc 和 realloc 来动态计算数组的大小。我不希望指定数组大小和元素本身,而是希望程序要求用户输入并且用户输入数组并在那里确定大小。这一切都应该是动态的。我不知道这是怎么做到的。谁能帮帮我!谢谢!

我还必须解释如何将数组添加到自身,结果保存在“a”中,原始数组丢失被总和代替。我该如何解释?

【问题讨论】:

  • 如果您希望数组是动态的,您必须修改ADDER 函数以接收一个或两个更多参数,即数组的大小。否则ADDER 无法知道数组的大小。
  • 可以修改ADDER的签名吗?如果是这样,按照建议,将其更改为这些行 void ADDER(int array1[], unsigned int size_of_array1, int array2[], unsigned int size_of_array2) 上的内容并传递每个数组的大小
  • 不,我无法更改 ADDER(a,a)
  • @JoachimPileborg ADDER 应该只有两个参数,我必须使用全局变量

标签: c arrays dynamic allocation


【解决方案1】:

这是你的程序的样子

int size; //global variable

void ADDER(int *a, int *b) {
    int i;
    for (i = 0; i < size; i++) {
        b[i] += a[i];
    }    
}

int main(){
    //ask the user to input the size and read the size
    int *a = (int *)malloc(size*sizeof(int));
    int *b = (int *)malloc(size*sizeof(int));

    //fill up the elements
    Adder(a,b);
    //print out b
    free(a->array);
    free(b->array);
}

虽然使用全局变量并不明智,但这里的底线是加法器需要以某种方式知道数组的大小,并且您需要以某种方式将大小传递给加法器函数。如果不能通过参数完成,则必须使用全局变量。

另一种选择是使用结构。

typedef struct myArray{
    int *array;
    int length;
}ARRAY;

void ADDER(ARRAY *a, ARRAY *b) {
    int i;
    for (i = 0; i < b->length; i++) {
        b->array[i] += a->array[i];
    }    
}

int main(){
    int size; //local variable
    //ask the user to input the size and read into the 'size' variable
    ARRAY *a, *b;
    a->array = (int *)malloc(size*sizeof(int));
    b->array = (int *)malloc(size*sizeof(int));
    a->length = b->length = size;

    //fill up the elements
    Adder(a,b);
    //print out b.array
    free(a->array);
    free(b->array);
}

【讨论】:

  • 最好不要在 C 中对 malloc 的返回值进行类型转换,同时提及 free 会很好!
  • 谢谢,但我必须使用 ADDER(a,a) 而不是 (a,b)。你认为在这种情况下它会起作用吗?
  • @another.anon.coward:更新了 free() 块!
  • @HelloWorld:在这种情况下,您不需要分配 b。只需调用 ADDER(a,a) 就可以了!
  • Err...你在哪里为 a & b 分配内存?!!
【解决方案2】:

这样的事情怎么样:

size_t length;

void ADDER(int *a, int *b)
{
    for (int i = 0; i < length; i++)
    {
        /* Add the arrays */
    }
}

int main()
{
    /* Get the number of entries in the arrays from the user */
    /* Store the result in the global variable "length" */
    /* Check the "scanf" function for that */

    int *a;
    /* Allocate the array */
    /* Remember that "malloc" wants the size in bytes, not number of items in the array */

    /* Get all items for the array from the user */

    /* Now add the array to itself */
    ADDER(a, a);

    /* Print the result */

    /* Free the array, a very important step! */
}

正如您所看到的,它不是完整的代码,但提供了关于应该做什么以及在哪里做的提示。希望对您有所帮助。

编辑 2 关于“参考”一词的注释。在 C 和 C++ 中,引用的使用是不同的。您使用int (&amp;a)[SIZE] 声明ADDER 函数的方式使用带有&amp; 的C++ 功能。在纯 C 中,“引用”只是一个指针。请参阅this SO question,了解有关该部分的一些好的答案。

【讨论】:

  • ADDER 应该只有两个参数
  • 它应该是同一个数组。加法器(a,a)
【解决方案3】:

除非您分配一个作为哨兵的附加元素,否则无法确定动态分配的数组的大小,即包含一个在实际数组元素中永远不会有效的值。另一种解决方案是将元素的数量放在第一个数组元素中。

如果您在编译时知道大小(并且根据您的代码这样做!),您可以在迭代数组时简单地使用相同的常量:

for (i = 0; i < SIZE; i++) {
    b[i] += a[i];
}

【讨论】:

  • 我想我必须在编译和比较期间获取大小。但是我在哪里使用 malloc ?这是一个要求。
  • 询问用户数组中元素的数量,然后按照此处所述使用 malloc roseindia.net/c-tutorials/c-dynamic-array.shtml
【解决方案4】:

您必须在单个 int 变量中读取用户输入。之后,您必须为 int 数组再分配一个空间,然后继续将数字插入到您的数组中。

 int main() {
   int inpt;   //user input.
   int inptcnt=0;  //amount of numbers given by the user.
   char flag='y';    //use this char to know if the user wants to insert another number or no.
   int *inptarray; //this pointer will be your int array.

   inptarray = (int *) malloc (sizeof(int));  //Here you generate the first entry for your array.
   if (inptarray == NULL) {   //Never forget to check if Malloc and Realloc failed.
         printf("Memory Error!!!\n);
         exit(1);
   }

   while (flag == 'y') {
     printf("Please enter a number:");
     scanf("%d", inpt);  //you ask from the user to input a number
     inptcnt++;  //You add one to the amount of numbers you have been given.
     printf("\nIf you wish to enter another number as well please press 'y'. Press anything else if you dont:");
     scanf(" %c", flag);
     inptarray[inptcnt - 1] = inpt;   //You add the number given by the user to your array.
     if (flag != 'y') {
       break;
     } else {

       realloc(inptarray, inptcnt * sizeof(int));  // Here you add space for the new entry to your array.
       if (inptarray == NULL) {   //Never forget to check if Malloc and Realloc failed.
         printf("Memory Error!!!\n);
         exit(1);
       }
     }
   }
 }

这是根据用户输入生成所需大小的数组的方法。 您可以通过 inptcnt 变量访问此数组的大小值。存储在此变量中的数字是数组的大小和您拥有的用户输入量。也不要忘记在使用完数组来释放声明的内存后调用 free(inptarray) 。

【讨论】:

    猜你喜欢
    • 2019-06-02
    • 2019-03-31
    • 2019-02-02
    • 2014-01-11
    • 2011-10-08
    • 1970-01-01
    • 1970-01-01
    • 2015-03-27
    相关资源
    最近更新 更多