I have the following:
struct matrix {
int h;
int w;
int** data;
};
int m1[2][2] = {
{1, 2},
{3, 4}
};
int m2[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
struct matrix matrix1 = {2, 2, m1};
struct matrix matrix2 = {3, 3, m2};
This gives the error 'initialisation from incompatible pointer type'. What pointer type should I be using?
You may be interested in the variable length arrays of C99. This solution does not directly answer your question about how to initialize the structure with a properly typed data (one can't); but you can use a simple pointer to store the array's address and then cast to the variable length array pointer when using struct matrix.
The user side would just call functions like printFroMat() which receive a single argument of type struct matrix; the code inside these functions (so to speak, the library implementation) would perform the somewhat unsightly casts, as demonstrated. The typedef makes the cast perhaps a little more understandable because it demonstrates where the variable name in a declaration would go.
Note that the funny sizeof(m2)/sizeof(*m2) etc. are not strictly necessary, you can just say 3. But the sizeof expression automatically stays in sync with the actual matrix size, which quickly becomes a real asset.
You can pass "arrays" (in fact: still just addresses, but of a known array type) together with their dimensions as parameters to functions, and index them the normal way (below in printMatrix). Example:
#include<stdio.h>
#include<string.h>
struct matrix {
int h;
int w;
int *data; // first element of matrix
};
int m2[4][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12}
};
void printMatrix(int dim1, int dim2, int mat[][dim2] )
{
printf("Address of matrix: %p\n", (void *)mat);
for(int i1=0; i1<dim1; i1++)
{
for(int i2=0; i2<dim2; i2++)
{
printf("%d ", mat[i1][i2]);
}
putchar('\n');
}
}
void printFromMat(struct matrix mat)
{
printMatrix(mat.h, mat.w, (int (*)[mat.w])mat.data);
// or:
typedef int (*mT)[mat.w];
printMatrix(mat.h, mat.w, (mT)mat.data);
}
int main()
{
printMatrix( sizeof(m2) /sizeof(*m2), // number of highest-order elements
sizeof(*m2)/sizeof(**m2), // number of second-order elements per highest-order
m2 ); // address of the first sub-array
struct matrix mat = { sizeof(m2) /sizeof(*m2), sizeof(*m2)/sizeof(**m2), *m2 };
printFromMat(mat);
return 0;
}
Sample session:
$ gcc -std=c99 -Wall -o 2d-matrix 2d-matrix.c && ./2d-matrix
Address of matrix: 0x100402020
1 2 3
4 5 6
7 8 9
10 11 12
Address of matrix: 0x100402020
1 2 3
4 5 6
7 8 9
10 11 12
Address of matrix: 0x100402020
1 2 3
4 5 6
7 8 9
10 11 12
2d array is not a pointer to pointer.
How to use the void *.
#include <stdio.h>
struct matrix {
int h;
int w;
void *data;
};
int m1[2][2] = {
{1, 2},
{3, 4}
};
int m2[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
struct matrix matrix1 = {2, 2, m1};
struct matrix matrix2 = {3, 3, m2};
int main(void){
int i, j;
int (*matp)[matrix2.w] = matrix2.data;//Back from the void* to pointer to array
for (i=0; i<matrix2.h; i++){
for(j=0; j<matrix2.w; j++)
printf("%d ", matp[i][j]);
puts("");
}
printf("\n");
return 0;
}
A matrix, as you declared, is not a pointer to pointer. Use a simple pointer to point its element.
#include <stdio.h>
struct matrix {
int h;
int w;
int* data;
};
int m1[2][2] = {
{1, 2},
{3, 4}
};
int m2[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
struct matrix matrix1 = {2, 2, &m1[0][0]};
struct matrix matrix2 = {3, 3, &m2[0][0]};
int main(int argc, char **argv)
{
int i, j;
for (i=0; i<matrix2.h; i++)
for(j=0; j<matrix2.w; j++)
printf("%d ", matrix2.data[(i*matrix2.h)+j]);
printf("\n");
}
EDIT
To answer to the comment, you can use compound literal as below. In this way you could access it with [i][j]
#include <stdio.h>
struct matrix {
int h;
int w;
int** data;
};
int *m2[3] = {
(int[]){1, 2, 3},
(int[]){4, 5, 6},
(int[]){7, 8, 9}
};
struct matrix matrix2 = {3, 3, m2};
int main(int argc, char **argv)
{
int i, j;
for (i=0; i<matrix2.h; i++)
for(j=0; j<matrix2.w; j++)
printf("%d ", matrix2.data[i][j]);
printf("\n");
}
You may not initialize the structure such a way like
struct matrix matrix1 = {2, 2, m1};
struct matrix matrix2 = {3, 3, m2};
because there is no conversion from types int ( * )[2] and int ( * )[3] to type int **
I suggest to allocate memory for copies of the arrays dynamically.
The approach can look the following way as it is shown in the demonstrative program
#include <stdlib.h>
#include <stdio.h>
struct matrix
{
size_t h;
size_t w;
int **data;
};
int m1[2][2] =
{
{ 1, 2 },
{ 3, 4 }
};
int m2[3][3] =
{
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
struct matrix init( size_t h, size_t w, int a[h][w] )
{
struct matrix matrix = { 0 };
matrix.data = malloc( h * sizeof( int * ) );
if ( matrix.data )
{
matrix.h = h;
matrix.w = w;
for ( size_t i = 0; i < h; i++ )
{
matrix.data[i] = malloc( w * sizeof( int ) );
if ( matrix.data[i] )
{
for ( size_t j = 0; j < w; j++ ) matrix.data[i][j] = a[i][j];
}
}
}
return matrix;
}
int main( void )
{
struct matrix matrix1 = init( 2, 2, m1 );
struct matrix matrix2 = init( 3, 3, m2 );
for ( size_t i = 0; i < matrix1.h; i++ )
{
for ( size_t j = 0; j < matrix1.w; j++ ) printf( "%d ", matrix1.data[i][j] );
printf( "\n" );
}
printf( "\n" );
for ( size_t i = 0; i < matrix2.h; i++ )
{
for ( size_t j = 0; j < matrix2.w; j++ ) printf( "%d ", matrix2.data[i][j] );
printf( "\n" );
}
printf( "\n" );
// free allocated arrays of matrix1 and matrix2
}
The program output is
1 2
3 4
1 2 3
4 5 6
7 8 9
You need also to write a function that will free the allocated memory for the structure.
The compiler must support variable length arrays.
Related
This function f is to find common elements in an array and return result array and i am using 4 four loops to accomplish this task which i feel is no the best use of the loops,
Another problem is, how can i determine the size of the returned array so that my loop is within bounds
here is the code
#include <stdio.h>
#include <stdlib.h>
int *f(int first[], int second[], int size_first, int size_second);
int main(void) {
int arr1[]={1, 8, 3, 2, 6};
int arr2[]= {2, 6, 1};
int size1 = sizeof(arr1)/sizeof(arr1[0]);
int size2 = sizeof(arr2)/sizeof(arr2[0]);
int *intersection = f(arr1, arr2, size1, size2);
for(int i=0;i<3; i++){
printf("%d ", intersection[i]);
}
return 0;
}
// function to find common elements in 2 arrays
int *f(int first[], int second[], int size_first, int size_second){
int k=0, count=0;
//loop through the array to find the number common elements and store in count for dynamic memory allocation in future
for(int i=0;i<size_first;i++){
for(int j=0;j<size_second;j++){
if(first[i]==second[j]){
count ++;
}
}
}
// allocate memory for the common elements by making use of count
int * common_elements = (int*)malloc(count*sizeof(int));
// store the common elements in the new memory location
for(int i=0;i<size_first;i++){
for(int j=0;j<size_second;j++){
if(first[i]==second[j]){
common_elements[k]=first[i];
k++;
}
}
}
return common_elements;
free(common_elements);
}
If you are allowed to waste some memory, note that the intersection cannot have cardinality larger than the number of elements in the smaller set. Therefore, you can allocate more memory than you might need and avoid having to count first and allocate later.
Or, you can realloc as you go.
In general, you need a good data structure for checking set membership more quickly than scanning an entire array although for small sizes which fit in various caches, the linear scan will not perform too shabbily either.
For larger sets, however, you'll want to load the larger of the sets into an AVL tree or Scapegoat tree.
For really large data sets, you'll need to look into Bloom filters and related data structures depending on the use case.
I am including below the most naive improvement in your code which still has the nested loop and wastes memory up to the size of the smaller set to avoid counting common elements first.
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
// TODO: What about duplicates in smaller set?
int *
int_set_intersection(
const int *first,
const int *second,
const size_t size_first,
const size_t size_second,
size_t *n
)
{
size_t K = 0; // number of common elements
const int is_first_smaller = (size_first < size_second);
// Done this way so I can declare variables as consts
const int *set_smaller = is_first_smaller ? first : second;
const int *set_larger = is_first_smaller ? second : first;
const size_t size_smaller = is_first_smaller ? size_first : size_second;
const size_t size_larger = is_first_smaller ? size_second : size_first;
int *common = malloc(size_smaller * sizeof(*common));
if (!common) {
fprintf(stderr, "Failed to allocate memory for %z ints\n", size_smaller);
perror("Cannot allocate memory for common elements");
exit(EXIT_FAILURE);
}
for (size_t i = 0; i < size_smaller; ++i) {
for (size_t j = 0; j < size_larger; ++j) {
if (set_smaller[i] == set_larger[j]) {
common[K] = set_smaller[i];
++K;
break;
}
}
}
*n = K;
return common;
}
void
int_set_print(const int *set, size_t n, FILE *f)
{
FILE *out = f ? f : stdout;
size_t i = 0;
fputs("{ ", out);
for (i = 0; i < n - 1; ++i) {
fprintf(out, "%d, ", set[i]);
}
fprintf(out, "%d }\n", set[i]);
}
int
main(void) {
int arr1[] = {1, 8, 3, 2, 6};
int arr2[] = {2, 5, 1};
size_t n = 0;
const int *intersection = int_set_intersection(
arr1,
arr2,
sizeof(arr1)/sizeof(arr1[0]),
sizeof(arr2)/sizeof(arr2[0]),
&n
);
int_set_print(intersection, n, NULL);
free(intersection); // not really needed, but good hygiene
return 0;
}
For larger arrays, one option is to sort the contents first to make it easier to check for common elements, as shown in the code below. If the original array contents cannot be changed, first copy them into dynamically allocated memory. Dynamically allocated memory is also needed to hold the list of common elements, but that can use the same storage as one of the copies.
OP's original function returns a pointer to dynamically allocated memory containing the array of common elements, but does not indicate the length of the array. I added a parameter to return the length.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int *f(int first[], int second[], int size_first, int size_second, int *size_common);
int main(void) {
int arr1[]={1, 8, 3, 2, 6};
int arr2[]= {2, 6, 1};
int size1 = sizeof(arr1)/sizeof(arr1[0]);
int size2 = sizeof(arr2)/sizeof(arr2[0]);
int size_common;
int *intersection = f(arr1, arr2, size1, size2, &size_common);
for(int i=0;i<size_common; i++){
printf("%d ", intersection[i]);
}
free(intersection);
return 0;
}
static int cmp_int(const void *ap, const void *bp) {
int a = *(const int *)ap;
int b = *(const int *)bp;
return (a > b) - (a < b);
}
// function to find common elements in 2 arrays
int *f(int first[], int second[], int size_first, int size_second,
int *size_common) {
int *copy1;
int *copy2;
int idx1;
int idx2;
int count;
// allocate memory local copies of the arrays
copy1 = malloc(size_first * sizeof (int));
copy2 = malloc(size_second * sizeof (int));
if (!copy1 || !copy2) {
// allocation error
free(copy1);
free(copy2);
*size_common = -1; // use -1 to report error
return NULL;
}
// copy the arrays
memcpy(copy1, first, size_first * sizeof (int));
memcpy(copy2, second, size_second * sizeof (int));
// sort the copies in ascending order
qsort(copy1, size_first, sizeof (int), cmp_int);
qsort(copy2, size_second, sizeof (int), cmp_int);
// find common elements
idx1 = 0;
idx2 = 0;
count = 0;
while (idx1 < size_first && idx2 < size_second) {
if (copy1[idx1] < copy2[idx2]) {
idx1++;
} else if (copy1[idx1] > copy2[idx2]) {
idx2++;
} else {
// common element found!
// use copy1[] to store common elements
copy1[count] = copy1[idx1];
count++;
idx1++;
idx2++;
}
}
// common elements are in copy1[].
// finished with copy2, so free it.
free(copy2);
if (count == 0) {
// no common elements
free(copy1); // free the memory
copy1 = NULL; // and make the function return NULL
} else {
// try to reduce memory for common elements
copy2 = realloc(copy1, count * sizeof (int));
if (copy2) {
// reallocation successful
copy1 = copy2;
} // else, never mind, copy1 is still valid
}
// return the common elements
*size_common = count;
return copy1;
}
If your arrays are of comparable elements (you use integers, which are comparable), the best way in my opinion is to sort both arrays and traverse both in parallel, looking at both sides and comparing the elements at both sides. If there's a lowest element, advance its pointer, leaving the other waiting.... if there's a match (they are equal), you can mark it (more on this later) and advance both pointers, until you reach the end in one array (the sortest). You will get the marks on the matching positions, but if you reorder the array, exchanging the found element with the first of the yet, unmatched elements, you will have all matching elements in the first positions of both arrays, letting you to return only the number of matches from the function and the matches themselves in the first positions of both arrays.
The complexity of this algorithm should be O(n*log(n)) (because of the quicksorts) if you use quicksort, plus O(n) (which doesn't affect the final O) for the matching, so O(n*log(n)) should be the big O complexity, as a general case. Below is a sample code, with a run:
comp.c
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#define N(arr) (sizeof(arr)/sizeof((arr)[0]))
void swap(int *ref_a, int *ref_b)
{
if (ref_a == ref_b)
return; /* nothing to do. */
int temp = *ref_a;
*ref_a = *ref_b;
*ref_b = temp;
}
int int_cmp(const void *_a, const void *_b)
{
const int *a = _a, *b = _b;
return *a - *b;
}
void print(int v[], int v_sz, const char *fmt, ...)
{
va_list p;
va_start(p, fmt);
vprintf(fmt, p);
va_end(p);
char *sep = "[";
for (int i = 0; i < v_sz; i++) {
printf("%s%d", sep, v[i]);
sep = ", ";
}
printf("]\n");
}
int find_matches(int a[], int b[], int a_sz, int b_sz)
{
print(a, a_sz, "a(unsorted)");
print(b, b_sz, "b(unsorted)");
qsort(a, a_sz, sizeof a[0], int_cmp);
qsort(b, b_sz, sizeof b[0], int_cmp);
print(a, a_sz, "a(sorted)");
print(b, b_sz, "b(sorted)");
int i = 0;
for (int i_a = 0, i_b = 0; i_a < a_sz && i_b < b_sz;) {
if (a[i_a] < b[i_b]) {
i_a++;
continue;
} else if (a[i_a] > b[i_b]) {
i_b++;
continue;
}
/* a[i_a] == b[i_b] */
swap(&a[i_a], &a[i]);
swap(&b[i_b], &b[i]);
print(a, a_sz, "after #%d, a:", i);
print(b, b_sz, "after #%d, b:", i);
i_a++; i_b++; i++;
}
return i;
}
int main()
{
int arr1[] = {1, 8, 3, 2, 6, 7};
int arr2[] = {2, 6, 1, 7, 4, 1, 9, 6};
int size1 = N(arr1);
int size2 = N(arr2);
int match = find_matches(arr1, arr2, size1, size2);
for (int i = 0; i < match; i++) {
printf("Match #%d: %d\n", i, arr1[i]);
}
}
It will produce:
$ comp
a(unsorted)[1, 8, 3, 2, 6, 7]
b(unsorted)[2, 6, 1, 7, 4, 1, 9, 6]
a(sorted)[1, 2, 3, 6, 7, 8]
b(sorted)[1, 1, 2, 4, 6, 6, 7, 9]
after #0, a:[1, 2, 3, 6, 7, 8]
after #0, b:[1, 1, 2, 4, 6, 6, 7, 9]
after #1, a:[1, 2, 3, 6, 7, 8]
after #1, b:[1, 2, 1, 4, 6, 6, 7, 9]
after #2, a:[1, 2, 6, 3, 7, 8]
after #2, b:[1, 2, 6, 4, 1, 6, 7, 9]
after #3, a:[1, 2, 6, 7, 3, 8]
after #3, b:[1, 2, 6, 7, 1, 6, 4, 9]
Match #0: 1
Match #1: 2
Match #2: 6
Match #3: 7
$ _
A good interface is to switch in both algorithms the matched elements with the first of the non-yet-matched elements in both arrays, so in this way you can return an integer (the one you use to know the start of the non-yet-matched elements) that tells you the number of matched elements, and you will get them from any of the two arrays.
If the elements are not comparable, and they can be just be compared for equity, then you have to compare each element with any other for a match, take them off from the arrays (this can be done swapping them with the first of the not yet matched elemnts, and advance the pointers), and start again with the reduced versions of them. Some way of doing this is, when you find a match, to exchange them with the first, second, third elements of each array, and use a variation of the above algorithm (you reorder as you match) In this case you compare at first time n*m (but not all), when you get a match, (n-1)*(m-1), ... and so until the last comparition in which you fail all comparitions to (m-k)*(n-k). This is, in the average, m*n/2 + (m-1)*(n-1)/2 +...+ (m-k)*(n-k). something in the range of m(m-1)*n(n-1)/k^2, which is O(m^2*n^2):
comp2.c
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#define N(arr) (sizeof(arr)/sizeof((arr)[0]))
void swap(int *ref_a, int *ref_b)
{
if (ref_a == ref_b)
return; /* nothing to do. */
int temp = *ref_a;
*ref_a = *ref_b;
*ref_b = temp;
}
int int_cmp(const void *_a, const void *_b)
{
const int *a = _a, *b = _b;
return *a - *b;
}
void print(int v[], int v_sz, const char *fmt, ...)
{
va_list p;
va_start(p, fmt);
vprintf(fmt, p);
va_end(p);
char *sep = "[";
for (int i = 0; i < v_sz; i++) {
printf("%s%d", sep, v[i]);
sep = ", ";
}
printf("]\n");
}
int find_matches(int a[], int b[], int a_sz, int b_sz)
{
print(a, a_sz, "a(unsorted)");
print(b, b_sz, "b(unsorted)");
int i = 0;
loop:
for (int i_a = 0; i_a + i < a_sz; i_a++) {
for (int i_b = 0; i_b + i < b_sz; i_b++) {
/* we can only compare for equality */
if (a[i + i_a] == b[i + i_b]) {
swap(&a[i + i_a], &a[i]);
swap(&b[i + i_b], &b[i]);
i++;
goto loop;
}
}
}
print(a, a_sz, "a(final)");
print(b, b_sz, "b(final)");
return i;
}
int main()
{
int arr1[] = {1, 8, 3, 2, 6, 7};
int arr2[] = {2, 6, 1, 7, 4, 1, 9, 6};
int size1 = N(arr1);
int size2 = N(arr2);
int match = find_matches(arr1, arr2, size1, size2);
for (int i = 0; i < match; i++) {
printf("Match #%d: %d\n", i, arr1[i]);
}
}
which produces, when running, the following output:
$ comp2
a(unsorted)[1, 8, 3, 2, 6, 7]
b(unsorted)[2, 6, 1, 7, 4, 1, 9, 6]
a(final)[1, 2, 6, 7, 3, 8]
b(final)[1, 2, 6, 7, 4, 1, 9, 6]
Match #0: 1
Match #1: 2
Match #2: 6
Match #3: 7
$ _
You can reorder the values, there's no difference, in this case you had a two level for loop, mixed with a third level go back to the beginning and start again loop. The loop is warranted to finish, as when you go back to the top, you have increased i, which means the nested for loops will be shorter each time. We can rewrite the find_matches routine in this case by adjusting the array start points, in this manner:
comp3.c
/* ... as before */
int find_matches(int a[], int b[], int a_sz, int b_sz)
{
print(a, a_sz, "a(unsorted)");
print(b, b_sz, "b(unsorted)");
int i = 0;
loop:
for (int i_a = 0; i_a < a_sz; i_a++) {
for (int i_b = 0; i_b < b_sz; i_b++) {
/* we can only compare for equality */
if (a[i_a] == b[i_b]) {
swap(&a[i_a], &a[0]);
swap(&b[i_b], &b[0]);
i++;
print(a++, a_sz--, "a(after match)");
print(b++, b_sz--, "b(after match)");
goto loop;
}
}
}
print(a, a_sz, "a(final)");
print(b, b_sz, "b(final)");
return i;
}
/* ... as before */
that will produce this result (I changed the initial sort order to see how it affects the final result):
$ comp3
a(unsorted): [7, 8, 2, 3, 6, 1]
b(unsorted): [2, 6, 1, 7, 4, 1, 9, 6]
a(after match): [7, 8, 2, 3, 6, 1]
b(after match): [7, 6, 1, 2, 4, 1, 9, 6]
a(after match): [2, 8, 3, 6, 1]
b(after match): [2, 1, 6, 4, 1, 9, 6]
a(after match): [6, 3, 8, 1]
b(after match): [6, 1, 4, 1, 9, 6]
a(after match): [1, 8, 3]
b(after match): [1, 4, 1, 9, 6]
a(final): [8, 3]
b(final): [4, 1, 9, 6]
Match #0: 7
Match #1: 2
Match #2: 6
Match #3: 1
$ _
I wrote this code :
#include <stdio.h>
void transpose(int *Al[]){
int x=0;
int z=0;
int k=1;
while (*Al[z] != "\0") {
int c=*Al[z];
if (c>x)
x=c;
z++;
}
printf("%d ",x);
for(int o=0;o<6;o++){
for(int i=0 ;i<x;i++ ) {
int *p = Al[i];
int l=*p;
if(k<l)
printf("%d ",*(p+k));
else
printf(" ");
}
k++;
printf("\n");
}
}
int main() {
int A[] = {5, -5, 14, 5, 2};
int B[] = {3, 6, 11};
int C[] = {4, 1, -3, 4};
int D[] = {6, 2, 7, 1, 8, 2};
int E[] = {2, 15};
int F[] = {3, 4, -2};
int *All[] = {A, B, C, D, E, F, NULL};
transpose(All);
}
The function gets an array that points to different array I need to print the arrays using pointers
the output should be :
-5 6 1 2 15 4
14 11 -3 7 -2
5 4 1
2 8
2
But this code doesn't print anything.
Also the arrays that it points at the first value is the size of the array.
I tried this :
void transpose(int *Al[]){
int x=0;
int z=0;
int k=1;
for(int o=0;o<5;o++){
for(int i=0 ;i<6;i++ ) {
int *p = Al[i];
int l=*p;
if(k<l)
printf("%d ",*(p+k));
else
printf(" ");
}
k++;
printf("\n");
}
}
It worked only I need to replace the five and six in the loop
Five is the biggest size of all he arrays -1 so I will know how many lines to print and six to how many arrays in All so I can know how many colums I should print. Is there a solution for this?
The condition in the while loop
while (*Al[z] != "\0") {
does not make a sense. The expression *Al[z] has the type int while the string literal "\0" has the type char *.
Also it is unclear why there is present the magic number 6 in this loop
for(int o=0;o<6;o++){
There is no need to calculate explicitly the number of columns because you have a sentinel value equal to NULL.
I can suggest for example the following solution
#include <stdio.h>
void transpose( int * Al[] )
{
int rows = 0;
for ( int **p = Al; *p != NULL; ++p )
{
if ( rows < **p ) rows = **p;
}
if ( rows ) --rows;
for ( int i = 0; i < rows; i++ )
{
for ( int **p = Al; *p != NULL; ++p )
{
if ( i + 1 < **p ) printf( "%2d ", *( *p + i + 1 ) );
else printf( " " );
}
putchar( '\n' );
}
}
int main(void)
{
int A[] = {5, -5, 14, 5, 2};
int B[] = {3, 6, 11};
int C[] = {4, 1, -3, 4};
int D[] = {6, 2, 7, 1, 8, 2};
int E[] = {2, 15};
int F[] = {3, 4, -2};
int *All[] = { A, B, C, D, E, F, NULL };
transpose( All );
return 0;
}
The program output is
-5 6 1 2 15 4
14 11 -3 7 -2
5 4 1
2 8
2
I am trying to make a function that is able to recognize if Winning_order arrays integers are within Order1,Order2,Order3. In Order1 the first row of Winning_order is present {1,2,3} as well as in order2. However in Order3 none of the elements correlate to the values of Winning_order so it is not a valid output.
int main(void)
{
int Order1[5] = {1,2,3}
int Order2[5] = {1,2,5,3}
int Order3[5] = {1,2,5}
int Winning_order[5][3] = {{1,2,3}, {4,5,6}, {7,8,9},{1,4,7},{2,5,8},{3,6,9},{1,5,9},{3,5,7}};
return 0;
}
Expected Output:
Order1
Order2
To expand on Jack Lilhammers's comment, you could do something like this:
#include <stdio.h>
int match_arrays(int *arr1, int *arr2, int len) {
for (int i = 0; i < len; i++) {
if (arr1[i] != arr2[i]) {
return 0;
}
}
return 1;
}
int main(void)
{
int Order1[3] = {1,2,3};
int Order2[4] = {1,2,5,3};
int Order3[3] = {1,2,5};
int Winning_order[8][3] = {{1,2,3}, {4,5,6}, {7,8,9},{1,4,7},{2,5,8},{3,6,9},{1,5,9},{3,5,7}};
for (int i = 0; i < 5; i++) {
if (match_arrays(Order1, Winning_order[i], 3)) {
printf("Order1");
}
if (match_arrays(Order2, Winning_order[i], 3)) {
printf("Order2");
}
if (match_arrays(Order3, Winning_order[i], 3)) {
printf("Order3");
}
}
return 0;
}
Be cause those are statically declared arrays, you have to use a series of if statements, or create a new array out of them, and it forces a lot to be hard coded.
EDIT: fixed include, dimensions, removed breaks, fixed function calls
Firstly, as #Jack Lilhammers pointed out, your expected output is incorrect if we can assume we understand what you are trying to accomplish: Your problem is essentially to check if an array is an element of an array-of-arrays.
This can be achieved like this:
#include <stdio.h>
int is_array_element(int rows, int columns, int arr1[rows][columns],
int arr2[columns]) {
for(int i = 0; i < rows; i++) {
for(int j = 0; j < columns; j++) {
if(arr1[i][j] != arr2[j]) {
break;
}
if(j == columns - 1) {
return 1;
}
}
}
return 0;
}
int main(void) {
/* as Order1 and Order3 have been declared as 5-arrays but are only
initialized with 3 integers, the remaining two elements are zero and
can (should) be ignored */
int Order1[5] = {1, 2, 3};
/* not clear how you wish to compare a 4-array with a 3-array and so
the code will clip the last element */
int Order2[5] = {1, 2, 5, 3};
int Order3[5] = {1, 2, 5};
int Winning_order[8][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9},
{1, 4, 7}, {2, 5, 8}, {3, 6, 9},
{1, 5, 9}, {3, 5, 7}
};
if(is_array_element(8, 3, Winning_order, Order1)) {
printf("Order1\n");
}
if(is_array_element(8, 3, Winning_order, Order2)) {
printf("Order2\n");
}
if(is_array_element(8, 3, Winning_order, Order3)) {
printf("Order3\n");
}
return 0;
}
And the output we get is:
Order1
I want create function which compares two arrays so that if they have the same values in a certain order (which may be maybe shifted) returns true.
For example
int arr1[] = {1,2,3,4,5}
int arr2[] = {3,4,5,1,2}
are the same, or true
while
int arr1[] = {1,2,3,4,5}
int arr2[] = {3,4,5,2,1}
are not same, and so false.
Any ideas?
Here you are
#include <stdio.h>
int is_equivalent(const int a[], const int b[], size_t n)
{
int success = 0;
for ( size_t m = 0; !success && m < n; )
{
// Try to find in the array a the first element of the array b
// If there is no such an element then the arrays are different.
// Otherwise compare elements of the arrays starting from the
// found element in a and the first element in b
while (m < n && a[m] != b[0]) ++m;
if (m != n)
{
size_t i = 1;
size_t j = ++m % n;
while (i < n && b[i] == a[j])
{
++i; ++j;
j %= n;
}
success = i == n;
}
}
return success;
}
int main( void )
{
{
int a[] = { 1, 2, 3, 4, 5 };
int b[] = { 3, 4, 5, 1, 2 };
printf("The arrays are equivalent: %d\n",
is_equivalent(a, b, sizeof(a) / sizeof(*a)));
}
{
int a[] = { 1, 2, 3, 4, 5 };
int b[] = { 3, 4, 5, 2, 1 };
printf("The arrays are equivalent: %d\n",
is_equivalent(a, b, sizeof(a) / sizeof(*a)));
}
return 0;
}
The program output is
The arrays are equivalent: 1
The arrays are equivalent: 0
try this
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
bool check(size_t size, int arr1[], int arr2[]){
int *temp = malloc(size * 2 * sizeof *temp);
memcpy(temp, arr1, size * sizeof *temp);
memcpy(temp+size, arr1, size * sizeof *temp);//[1,2,3] --> [1,2,3,1,2,3]
size_t i;
for(i = 0; i < size; ++i)
if(memcmp(temp+i, arr2, size * sizeof *temp) == 0)
break;
free(temp);
return i != size;
}
#define TEST(size, a1, a2) puts(check(size, a1, a2) ? "same" : "not same")
int main(void) {
int arr1[] = {1,2,3,4,5};
int arr2[] = {3,4,5,1,2};
int arr3[] = {3,4,5,2,1};
int arr4[] = {1, 0, 1, 1, 0};
int arr5[] = {1, 0, 1, 0, 1};
size_t size = sizeof(arr1)/sizeof(*arr1);
TEST(size, arr1, arr2);
TEST(size, arr1, arr3);
TEST(size, arr4, arr5);
}
Well, if the arrays are just rotated versions of each other, they must be of equal length and there must exist at least one offset, such that rotate(arr1, offset) == arr2.
Thus we know that concat(arr2, arr2) must be equivalent to rotate(concat(arr1, arr1), offset) and thus must contain arr1 without rotation at position offset.
And there we are with the classical substring-matching problem. There won't be any better solution to this problem than the algorithms to solve the former simply because they are equivalent.
A pretty simple solution to this problem would be elimination of probable offsets:
//generate a list of offsets from the first element in arr1
list offsets = indicesOf(arr1[0], arr2)
int i = 0
while !offsets.empty && i < length(arr1):
//generate the rotational offsets of the next char
list nextoffsets = indicesOf(arr1[i], arr2)
//make offsets the list of offsets that are valid for all elements up to arr1[i]
offsets = intersection(offsets, nextoffsets)
i++
return !offsets.empty
#include <stdio.h>
int isArraySame(int arr1[], int arr2[], int len1, int len2){
int var1=0;
int var2=0;
int index=0;
for (index=0;index<len1;index++){
var1+=arr1[index];
}
for (index=0;index<len2;index++){
var2+=arr2[index];
}
if (var1==var2) return 1;
return 0;
}
int main(){
int arr1[] = {1,2,3,4,5};
int arr2[] = {3,4,5,1,2};
if (isArraySame(arr1, arr2, 5, 5)) {
printf("true");
} else {
printf("false");
}
return 0;
}
You may be interested in the C++ equivalent for this. It's instructive to see how the Standard Library provides much higher-level abstractions than are available to the C programmer.
First of all, we'll want a sensible signature for our function. Let's make it a template, so we can use std::array as happily as std::vector and struct Foo as happily as int:
template<typename T>
bool equals_rotated(const std::vector<T>& a, const std::vector<T>& b);
And some simple tests:
int main()
{
const auto e = equals_rotated<int>;
return !e({}, {})
+ e({1, 2, 3, 4} , {1, 2, 3})
+ !e({1, 2, 3} , {1, 2, 3})
+ e({1, 2, 3, 4} , {1, 2, 4, 3})
+ !e({1, 2, 3, 4} , {4, 1, 2, 3})
;
}
The implementation is straightforward. We know that if the arrays differ in length then they can't be equivalent; conversely, if they are identical, they must be equivalent. So let's return early in those cases:
if (a.size() != b.size())
return false;
if (a == b)
return true;
For the general case, we can make a concatenation of a and itself, and then test whether that contains b as a subsequence. This will have an impact on the memory requirement, but it makes for a simple implementation:
auto v = a;
v.reserve(2*a.size());
std::copy(a.begin(), a.end(), std::back_inserter(v));
return std::search(v.begin(), v.end(), b.begin(), b.end()) != v.end();
If we put that all together, include the necessary headers, and add a wrapper so that we can call it from C, we get:
#include <algorithm>
#include <iterator>
#include <vector>
template<typename IterA, typename IterB>
bool equals_rotated(IterA a_begin, IterA a_end, IterB b_begin, IterB b_end)
{
// trivial tests
if (a_end - a_begin != b_end - b_begin)
return false;
if (std::equal(a_begin, a_end, b_begin, b_end))
return true;
// Otherwise, make a copy of a+a
std::vector<typename std::iterator_traits<IterA>::value_type> v;
v.reserve(2 * (a_end - a_begin));
const auto ins = std::back_inserter(v);
std::copy(a_begin, a_end, ins);
std::copy(a_begin, a_end, ins);
// and test whether it contains b
return std::search(v.begin(), v.end(), b_begin, b_end) != v.end();
}
template<typename T>
bool equals_rotated(const std::vector<T>& a, const std::vector<T>& b)
{
return equals_rotated(a.begin(), a.end(), b.begin(), b.end());
}
extern "C" {
bool is_rotated_array(int *a, size_t a_len, int *b, size_t b_len)
{
return equals_rotated(a, a+a_len, b, b+b_len);
}
}
int main()
{
const auto e = equals_rotated<int>;
return !e({}, {})
+ e({1, 2, 3, 4} , {1, 2, 3})
+ !e({1, 2, 3} , {1, 2, 3})
+ e({1, 2, 3, 4} , {1, 2, 4, 3})
+ !e({1, 2, 3, 4} , {4, 1, 2, 3})
;
}
I am having a hard time understanding where I can use a pointer to an array,
e.g: char (*a)[10];.
So two basic questions.
Please give me a simple example of how just a pointer to an array can be used in C code.
Why would one use it as apposed to just declaring a variable as a pointer and then incrementing/decrementing the address after that point.
Say you have a database query that returns a set of strings. Further, say that you know that these strings are no longer than 9 characters in length. Only, you don't know how many elements are in the set returned by the query.
char (*a)[10] = malloc( NumRecords * sizeof *a );
if ( a == NULL )
{
/* Handle error appropriately */
return EXIT_FAILURE; /* Naive */
}
for ( i = 0 ; i < NumRecords ; ++i )
{
assert(strlen(DbRecordSet[i]) < 10);
strcpy(a[i], DbRecordSet[i]);
}
Example: how to print the elements of an array of num_row rows and 3 columns:
#include <stdio.h>
#define NUM_ROW(x) (sizeof (x) / sizeof *(x))
// print elements of an array of num_row rows and 3 columns
void print(int (*a)[3], size_t num_row)
{
size_t num_col = sizeof *a / sizeof **a;
for (int i = 0; i < num_row; i++) {
for (int j = 0; j < num_col; j++) {
printf("%d\n", a[i][j]);
}
}
}
int main(void)
{
int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
int b[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
print(a, NUM_ROW(a));
print(b, NUM_ROW(b));
return 0;
}
Any time you pass an expression with a multi-dimensioned array type to a function, you're going to be working with a pointer to an array:
int a[10][20];
foo(a);
void foo(int (*p)[20]) // or int p[][20]
{ ... }