0

I have a problem in C. This is the question:

Develop a C function ADDER that adds two integer arrays together. ADDER should have only two parameters, which are the two arrays to be added. The second array argument will hold the sum of arrays on exit. Both parameters should be passed by reference.

Write a C program to test the ADDER function with the call ADDER (A, A) where A is an array to be added to itself. Array A can be of any size with any values. Write, compile, and execute the program.

Explain the results of the program.


So far I have solved it this way and it works just fine:

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

The problem is, I have to use dynamic arrays and use malloc and realloc in the program to compute the size of the array on the fly. Instead of specifying the array size and the elements itself, I want the program to ask the user for input and the user enters the array and the size is determined there. It should all be dynamic. I do not know how this is done. Can anyone please help me out! thanks!

Also I have to explain how the array is added to itself the result is saved in "a" and the original array is lost replaced by the sum. how can I explain this?

Amjad
  • 1,627
  • 5
  • 21
  • 41
  • If you want the arrays to be dynamic, you must modify the `ADDER` function to receive one or two more parameters that is the size of the arrays. Otherwise there is no way for `ADDER` to know the size of the arrays. – Some programmer dude Jan 03 '12 at 15:01
  • http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?id=1043284351&answer=1047673478 – ob_dev Jan 03 '12 at 15:13
  • Are you allowed to modify the signature of `ADDER`? If so, as suggested, change it to something on these lines `void ADDER(int array1[], unsigned int size_of_array1, int array2[], unsigned int size_of_array2)` and pass the size of each array – another.anon.coward Jan 03 '12 at 15:13
  • No I cannot change ADDER(a,a) – Amjad Jan 03 '12 at 15:15
  • @JoachimPileborg ADDER should have only two parameters my he must use a global variable – ob_dev Jan 03 '12 at 15:16
  • Are you sure that the original assignment didn't ask for something simple like "assume that each array is 10 elements long" or something like that? Otherwise you could consider delimiting the arrays with a sentinel value - that is, put an unused value at the end of the array that means that there is the end. You know, just like strings have '\0'. Or have the first element in the array be the number of elements. – Mr Lister Jan 03 '12 at 15:36
  • Your assignment is clearly ill specified. There is no good solution in C where you don't specify the size of the array(s) as argument. – Jens Gustedt Jan 03 '12 at 15:42
  • This `void ADDER(int (&a)[SIZE], int (&b)[SIZE])` isn't valid C. – alk Jan 10 '15 at 11:31

4 Answers4

3

Here is how your program would look like

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

ALthough its not wise to use globals, the bottom line here is that adder somehow needs to know the size of the array and somehow you need to convey the size to the ADDER function. If that can't be done through parameters, you have to use globals.

Another option would be to use structures.

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);
}
Chethan Ravindranath
  • 2,001
  • 2
  • 16
  • 28
1

How about something like this:

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! */
}

As you can see it's not complete code, but gives hints about what should be done, and where. Hope it helps somewhat.

Edit 2 A note about the word "reference". The usage of references is different in C and C++. The way you declared your ADDER function, with int (&a)[SIZE] uses a C++ feature with the &. In plain C a "reference" is simply a pointer. See this SO question for some good answers about that part.

Community
  • 1
  • 1
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

It is impossible to determine the size of a dynamically allocated array unless you allocate an additional element which works as a sentinel, i.e. contains a value that is never valid in real array elements. Another solution would be putting the number of elements in the first array element.

If you know the size at compile time (and according to your code you do so!), you can simply use the same constant when iterating over the array:

for (i = 0; i < SIZE; i++) {
    b[i] += a[i];
}
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • I think I have to get the sizes during compilation and compare. but where do I use malloc ? that is a requirement. – Amjad Jan 03 '12 at 15:03
  • Ask the user the number of elements in the array and then use malloc as described here http://www.roseindia.net/c-tutorials/c-dynamic-array.shtml – Manuel Selva Jan 03 '12 at 15:13
0

You will have to read user input in a single int variable. After that you will have to allocate one more space to your int array and then proceed to insert the number to your array.

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

This is how you can generate an array of whatever size you need, according to user input. You can access the size value of this array through the inptcnt variable. The number that is stored within this variable is the size of your array and the amount of user inputs you have. Also don't forget to call free(inptarray) after you are done using your array to free up the claimed memory.

Eternal_Light
  • 676
  • 1
  • 7
  • 21