I am trying to rewrite my code that takes the user input array, goes to the function and adds zeros between each number and saves it to array 2. My source code works just fine but I am having trouble trying to make it so that it uses pointer arithmetic just for the function to visit each array element, it cannot be sub scripting. What can you tell me about my code or suggestions on how to do this?
Source code:
#include <stdio.h>
void insert0(int n, int a1[], int a2[]);
int main(void) {
int i;
int n;
printf("Please enter the length of the input array: ");
scanf("%d", &n);
int a[n];
int b[2*n];
printf("Enter %d numbers for the array: ", n);
for (i = 0; i < n; i++){
scanf("%d", &a[i]);
}
insert0(n, a, b);
printf("Output array:");
for (i = 0; i < 2*n; i++){
printf(" %d", b[i]);
printf("\n");
}
return 0;
}
void insert0(int n, int a[], int b[]) {
int i, j = 0;
for(i = 0; i < n; i++, j+=2){
b[j]= a[i];
b[j+1] = 0;
}
}
My arithmetic:
#include <stdio.h>
void insert0(int n, int *a1, int *a2);
int main(void) {
int i;
int n;
printf("Please enter the length of the input array: ");
scanf("%d", &n);
int a1[n];
int a2[2*n];
printf("Enter %d numbers for the array: ", n);
for (i = 0; i < n; i++){
scanf("%d", &a2[i]);
}
//not sure if this is how you call it, I've seen it called with arr
insert0(n, a1, a2);
printf("Output array:");
for (i = 0; i < 2*n; i++){
printf(" %d", a2[i]);
printf("\n");
}
return 0;
}
void insert0(int n, int *a1, int *a2) {
int *p;
int j = 0;
// I think I translated this properly
for(p = a1; p < a1+n; p++, j+=2){
a2+j = a1+p;
//unsure how to get a2[j+1] to still work here with pointer
a2(j+1) = 0;
}
}