1
#include <stdio.h>

void add_adjacents() {
  int num1[5] = {1, 2, 3, 4, 5};
  int num2[5] = {10, 20, 30, 40, 50};
  int final[5];

  for (int i=0; i<sizeof(num1); i++) {
    final[i] = num1[i] + num2[i];
  }

  for (int c=0; c<sizeof(final)/sizeof(final[0]); c++) {
    printf("%d\n", final[c]);
  }
}

void main() {
  add_adjacents();
}

So, I did the above without the pointers. But with pointers, here is my attempt: I'm still new to pointers, and I'm playing with different practice problems.

#include <stdio.h>

void add_adjacents() {
  int num1[5] = {1, 2, 3, 4, 5};
  int num2[5] = {10, 20, 30, 40, 50};
  int final[5];


  for (; *num1 != '\0'; *num1++) {
    *final = *num1 + *num2;
  }

  for (int c=0; c<sizeof(final)/sizeof(final[0]); c++) {
    printf("%d\n", final[c]);
  }
}

void main() {
  add_adjacents();
}
4
  • 1
    i<sizeof(num1) --> i<sizeof(num1)/sizeof(*num1) Commented Feb 11, 2017 at 12:00
  • 1
    ideone.com/wz4cua Commented Feb 11, 2017 at 12:08
  • 1
    *num1++ : num1 is array, not pointer. *num1 != '\0' : 0 is not included in the array of num1 Commented Feb 11, 2017 at 12:10
  • Oh man! Your code makes so much sense !!! And yeah, I have to CREATE a pointer ... makes sense! Thank you so much. Commented Feb 11, 2017 at 12:12

1 Answer 1

1

The following does the trick:

void add_adjacents() {
  int num1[5] = {1, 2, 3, 4, 5};
  int num2[5] = {10, 20, 30, 40, 50};
  int final[5], c;

  int *n1= num1, *n2=num2, *f=final;

  for (; n1<&num1[5]; ) {
    *f++ = *n1++ + *n2++;
  }

  for (c=0; c<sizeof(final)/sizeof(final[0]); c++) {
    printf("%d\n", final[c]);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.