2012-01-03 23 views
0

私はCで問題があります。これは質問です。C - 動的配列を使用する

2つの整数配列を一緒に追加するC関数ADDERを作成します。 ADDERには、追加する2つの配列である2つのパラメータのみが必要です。 2番目の配列引数は、終了時に配列の合計を保持します。両方のパラメータは参照渡しする必要があります。

ADDER関数をADDER(A、A)という呼び出しでテストするためのCプログラムを作成します。ここで、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"に保存され、元の配列が合計で置き換えられたかについて説明しなければなりません。私はこれをどのように説明できますか?

+0

アレイを動的にする場合は、配列のサイズである1つまたは2つ以上のパラメータを受け取るように、「ADDER」関数を変更する必要があります。さもなければ、 'ADDER'が配列のサイズを知る方法はありません。 –

+0

申し訳ありませんが、どうですか? – Amjad

+0

http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?id=1043284351&answer=1047673478 – obo

答えて

3

がどのようにあなたのプログラムが希望グローバルを使用してその賢明ではないが

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

'malloc'の戻り値を型キャストしない方が良いC言語では、 'free'という言葉もいいでしょう! –

+0

まあありがとうございますが、私はADDER(a、a)を使わなくてはなりません(a、b)。あなたはそれがその場合にうまくいくと思いますか? – Amjad

+0

@ another.anon.coward:free()ブロックで更新されました! –

0

動的に割り当てられた配列のサイズを決定することは、センチネルとして動作する追加の要素を割り当てない限り、つまり実際の配列要素で決して有効ではない値を含む場合を除いては、不可能です。別の解決策は、第1の配列要素に要素の数を入れることである。

配列の繰り返し処理を行う場合、コンパイル時にサイズを知っている(とあなたのコードに応じて、あなたがそうでください!)、あなたは、単に同じ定数を使用することができた場合:

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

コンパイル時にサイズを取得して比較する必要があると思います。 mallocはどこで使うのですか?それは要件です。 – Amjad

+0

配列の要素の数を問い合わせて、ここで説明するようにmallocを使用してください。http://www.roseindia.net/c-tutorials/c-dynamic-array.shtml –

1

どのようにこのようなものについて:あなたは、それは完全なコードではないのですが、何をすべきかについてのヒントを与え、どこで見ることができます

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++では、参照の使い方が異なります。 ADDER関数を宣言する方法は、int (&a)[SIZE]で、&のC++機能を使用します。プレーンCでは、「参照」は単なるポインタです。その部分についての良い答えはthisです。

+0

ADDERには2つのパラメータ – obo

+0

しかなく、同じ配列にする必要があります。追加者(a、a) – Amjad

+1

@HelloWorld回答更新 –

0

ユーザー入力を単一の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)を呼び出すことを忘れないでください。

関連する問題