簡體   English   中英

C-使用動態數組

[英]C - using dynamic arrays

我的C語言有問題。這是一個問題:

開發一個將兩個整數數組加在一起的C函數ADDER。 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”中,原始數組丟失了,並被總和取代。 我該如何解釋?

這是您的程序的外觀

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);
}

盡管使用全局變量不是明智之舉,但這里的底線是加法器需要以某種方式知道數組的大小,並且需要以某種方式將大小傳遞給ADDER函數。 如果無法通過參數完成此操作,則必須使用全局變量。

另一種選擇是使用結構。

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);
}

這樣的事情怎么樣:

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 (&a)[SIZE]聲明ADDER函數的方式將C ++功能與& 在普通C語言中,“引用”只是一個指針。 有關部分的一些好的答案,請參見此SO問題。

除非您分配一個額外的元素作為哨兵,即包含一個在真實數組元素中永遠無效的值,否則無法確定動態分配的數組的大小。 另一種解決方案是將元素數量放入第一個數組元素中。

如果您知道編譯時的大小(並且根據您的代碼知道!),則可以在遍歷數組時簡單地使用相同的常量:

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

您將必須在單個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)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM