I have the following code, which works fine
#include <stdlib.h>
void transpose();
void main(){
transpose();
}
void transpose() {
int arr[] = {2, 3, 4, 1};
int l = sizeof (arr) / sizeof (arr[0]);
int i, j, k;
for (i = 0; i < l; i++) {
j = (i + 1) % l;
int copy[l];
for (k = 0; k < l; k++)
copy[k] = arr[k];
int t = copy[i];
copy[i] = copy[j];
copy[j] = t;
printf("{%d, %d, %d, %d}\n", copy[0], copy[1], copy[2], copy[3]);
}
}
However what I want to do is, pass an array to transpose function and the transpose function would return the list of arrays.
So I tried the following code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void print_array(int a[], int num_elements);
void main(){
int b[16];
int a[] = {2, 3, 4, 1};
c= transpose(a);
print_array(c,16);
}
int transpose(int arr) {
//int arr[] = {2, 3, 4, 1};
int b[16];
int l = sizeof (arr) / sizeof (arr[0]);
int i, j, k;
for (i = 0; i < l; i++) {
j = (i + 1) % l;
int copy[l];
for (k = 0; k < l; k++)
copy[k] = arr[k];
int t = copy[i];
copy[i] = copy[j];
copy[j] = t;
printf("{%d, %d, %d, %d}\n", copy[0], copy[1], copy[2], copy[3]);
b=copy;
}
return b;
}
void print_array(int a[], int num_elements)
{
int i;
for(i=0; i<num_elements; i++)
{
printf("%d ", a[i]);
}
printf("\n");
}
But some errors. I would like NOT to work with pointers, so how to tackle this?
Also I know the print_array function is defined to print single array, I will modify it to print all arrays by a for loop. Is that a correct approach?
cinmainint l = sizeof (arr) / sizeof (arr[0]);isn't going to work in your second program's function, since it receivesarras a pointer, not an array, as @CarlNorum mentions. You can't return arrays from functions in C, either, and you shouldn't return a pointer to an array local to your function, since it'll cease to exist when your function returns. Your best bet is probably to pass both arrays into your function.