printing multidimensional array in c - c

I am trying to print an array with specific dimensions, but it prints out wrong entities when it's run.
//code
#include <stdio.h>
int my_array[2] [4] = {
{1, 2, 3, 4}, {5, 6, 7, 8}
};
void print_array(const int h, const int w, char array[][w]) {
int nRow = h;
int nColumn = w;
for(int i = 0; i < nRow; i++) {
printf("--- Row %d --- \n", i);
for(int j = 0; j < nColumn; j++) {
printf("Column [%d] = %d \n", j, array[i] [j]);
}
}
}
int main(int argc, char **argv)
{
const int array_width = 4;
const int array_height = 2;
print_array(array_height, array_width, my_array);
return 0;
}
After compiling it prints out the next result:

Change char array[][w] to int array[][w] in the function print_array, which expects integer array. The compiler would have issued incompatible type warning, but that's easy to miss! Try to compile the program with zero warnings.

Related

Returning every s-th component of a vector abort problem in c

The task was to create a program in which you input a vector and it returnes every s-th component of the vector. For example, if x = (1, 2, 3, 4, 5, 6) and s = 2, the output is (1, 3, 5). But I get a zsh abort warning.
#include <stdio.h>
void sampleVector(double arr[], int n, int s){
int j = 0;
for (j=0; j<n; j++) {
arr[j] = 0;
printf("%d: ",j);
scanf("%lf",&arr[j]);
}
int i=1;
printf("%f,", arr[i]);
for (i=1; i<n; i++){
s=s*i;
printf("%f", arr[s]);
}
}
int main() {
int n;
scanf("%d", &n);
double arr[3]={0,0,0};
int s;
scanf("%d", &s);
sampleVector(arr, n, s);
}
This is my program so far!
void printfEveryNth(const int *array, size_t size, size_t n)
{
if(array && n)
{
for(size_t index = 0; index < size; index += n)
{
printf("%d ", array[index]);
}
printf("\n");
}
}
int main(void)
{
int array[] = {1, 2, 3, 4, 5, 6};
printfEveryNth(array, 6 , 2);
}
https://godbolt.org/z/e3Tsa8GKj

Remove negative numbers and sort an array

Good day everyone,
my task is to remove all negative numbers from an array, and shorten it (return the new length as the amount of positive numbers). I tried doing that by BubbleSort all negative number to the right, and new length would be (old length - number of swap). My code simply freezes up the system.
I would be grateful if you guys could help.
void swap(int *p, int *q) {
int h = *p;
*p = *q;
*q = h;
}
int remove_negatives(int *array, int length) {
int *a;
int n = length;
a = &array[n - 1];
for (int i = 0; i <= n - 1; i++) {
while (array < a) {
if (*array < 0) {
swap(a, array);
a--;
array++;
length--;
}
}
}
printialn(array, n);
return length;
};
int main(void) {
int a[] = {-1, 2, 4, -8, 3, 7, -8, 9, 3};
int l = sizeof(a) / sizeof(a[0]);
printiln(remove_negatives(a, l));
return 0;
}
The while loop never stops, that's probably the reason your code freezes.
Your code only changes the address when the if statement is true. Which the array in your main() will stuck on the second (a[1]) element. So if we change change the address when the if statement is false...
#include<stdio.h>
#include<stdlib.h>
void swap(int *p, int *q) {
int h = *p;
*p = *q;
*q = h;
}
int remove_negatives(int *array, int length) {
int *a, *head;
int n = length;
head = array;
a = &array[n - 1];
for (int i = 0; i <= n - 1; i++) {
while (array < a) {
if (*array >= 0) {
array++;
continue;
}
swap(a, array);
a--;
array++;
length--;
}
}
for (int i=0; i<length; i++) {
printf("%d ", *head);
head++;
}
puts("");
return length;
}
int main(void) {
int a[] = {-1, 2, 4, -8, 3, 7, -8, 9, 3};
int l = sizeof(a) / sizeof(a[0]);
remove_negatives(a, l);
return 0;
}
Now the while loop works, buts as #wovano said, the answer is still wrong. Your code isn't exactly a "bubble sort". you swap all the negative number to the end of the array and didn't actually sort the array.
So, let's start from the beginning.
To simplify the process, let bubble sort first, and then find the new array length.
#include<stdio.h>
#include<stdlib.h>
void swap(int *p, int *q) {
int h = *p;
*p = *q;
*q = h;
}
int bubble_sort(int *array, int length) {
int i, j;
// Bubble sort
for (i=0; i<length-1; i++) {
for (j=i+1; j<length; j++) {
if (array[i]<array[j]) swap(&array[i], &array[j]);
}
}
// Find new array length
for (i=length-1; i>=0; i--) {
if (array[i]>=0) break;
length--;
}
return length;
}
int main(void) {
int a[] = {-1, 2, 4, -8, 3, 7, -8, 9, 3};
int l = sizeof(a) / sizeof(a[0]);
l = bubble_sort(a, l);
for (int i=0; i<l; i++) printf("%d ", a[i]);
puts("");
return 0;
}

How to merge array elements with token merging ## operator???

I want to merge 3, 7, 1 to get 371. I want to know how to merge it???
#include <stdio.h>
int main(void)
{
int a[] ={3, 7, 1};
return(0);
}
I think rather than "merge", you want to convert array into an integer value, just like join operation that we see in Java variants. You can easily achieve this by iterating over the array :
#include <stdio.h>
int joinArray(int a[], int N) {
int i, res = 0;
for(i = 0; i < N; i++)
res = res*10 + a[i];
return res;
}
int main() {
int a[] = {3, 7, 1};
printf("merged res : %d\n", joinArray(a, 3));
return 0;
}
You could try something like this;
#include <stdio.h>
int main(void)
{
int a[] ={3, 7, 1};
int i, result = 0;
for(i=0;i<sizeof(a)/sizeof(a[0]);i++)
result += a[i] * pow(10, sizeof(a)/sizeof(a[0])-i-1);
printf("result %d\n", result);
return(0);
}

Why does this program segfault when returning a pointer to a local static variable?

This is related to an earlier question of mine. I tried expanding the code a little bit and to play around with different ways of returning pointers to local static variables, especially returning two-dimensional arrays. (This is seriously just to understand how pointers to arrays work and how they behave in function environments. It has not even the slightest intent of returning arrays the smart way using structs.) I wrote two functions both transpose matrices. The function transpose() only transposes 2x4-matrices and the function transpose_generic() is supposed to transpose matrices of arbitrary size. There is no real use to them. After I have declared and defined the functions I call them from int main(int argc, char *argv[]){}. The two matrices that have been transposed are supposed to be printed to stdout in a simple for-loop. And here is something I don't understand. Depending on whether I declare the matrices that are supposed to be transposed as global or local variables I get a segfault or "clean" exit. I can also prevent the compiled program from segfaulting by using a for loop after the for loop that prints the transposed matrices to stdout. But the for-loop needs to use a new index. I'm sure I'm missing something very basic but I cannot figure this out on my own. Even after extensive internet searching I'm still puzzled. So maybe someone can enlighten me. Here is the code:
Will segfault
#include <stdio.h>
int mat1[2][4] = {
{9, 10, 11, 12},
{13, 14, 15, 16}
};
int mat2[2][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8}
};
typedef matx[2];
matx *transpose(int matrix[][4]);
typedef maty[];
maty *transpose_generic(int nrow, int ncol, int matrix1[nrow][ncol], int matrix2[nrow][ncol]);
int main(int argc, char *argv[]) {
/* This may need a little bit of clarification. Here we want to declare a
* pointer to an array and we need the round brackets () for this. If we
* were simply to write *mat_transpose[2] we would declare an array of
* pointers since [] has higher precedence than *. */
int (*mat_transpose)[2];
int tmat[2][4];
int i;
int j;
mat_transpose = transpose(mat1);
transpose_generic(2, 4, mat2, tmat);
for (j = 0; j < 2; j++) {
for (i = 0; i < 4; i++) {
printf("mat_transpose[%d][%d] = %d\n", i, j, mat_transpose[i][j]);
printf("tmat[%d][%d] = %d\n", i, j, tmat[i][j]);
}
}
return 0;
}
matx *transpose(int matrix[][4]) {
static int mat[4][2];
int i;
int j;
printf("Transpose a 2x4 matrix\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 4; j++) {
mat[j][i] = matrix[i][j];
}
}
return mat;
}
maty *transpose_generic(int nrow, int ncol,
int matrix1[nrow][ncol],
int matrix2[nrow][ncol]) {
int i;
int j;
printf("Transpose a matrix\n\n");
for (i = 0; i < nrow; i++) {
for (j = 0; j < ncol; j++) {
matrix2[j][i] = matrix1[i][j];
}
}
return matrix2;
}
Will exit clean
#include <stdio.h>
typedef matx[2];
matx *transpose(int matrix[][4]);
typedef maty[];
maty *transpose_generic(int nrow, int ncol, int matrix1[nrow][ncol], int matrix2[nrow][ncol]);
int main(int argc, char *argv[]) {
int mat1[2][4] = {
{9, 10, 11, 12},
{13, 14, 15, 16}
};
int mat2[2][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8}
};
/* This may need a little bit of clarification. Here we want to declare a
* pointer to an array and we need the round brackets () for this. If we
* were simply to write *mat_transpose[2] we would declare an array of
* pointers since [] has higher precedence than *. */
int (*mat_transpose)[2];
int tmat[2][4];
int i;
int j;
mat_transpose = transpose(mat1);
transpose_generic(2, 4, mat2, tmat);
for (j = 0; j < 2; j++) {
for (i = 0; i < 4; i++) {
printf("mat_transpose[%d][%d] = %d\n", i, j, mat_transpose[i][j]);
printf("tmat[%d][%d] = %d\n", i, j, tmat[i][j]);
}
}
return 0;
}
matx *transpose(int matrix[][4]) {
static int mat[4][2];
int i;
int j;
printf("Transpose a 2x4 matrix\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 4; j++) {
mat[j][i] = matrix[i][j];
}
}
return mat;
}
maty *transpose_generic(int nrow, int ncol,
int matrix1[nrow][ncol],
int matrix2[nrow][ncol]) {
int i;
int j;
printf("Transpose a matrix\n\n");
for (i = 0; i < nrow; i++) {
for (j = 0; j < ncol; j++) {
matrix2[j][i] = matrix1[i][j];
}
}
return matrix2;
}
Will exit clean
#include <stdio.h>
int mat1[2][4] = {
{9, 10, 11, 12},
{13, 14, 15, 16}
};
int mat2[2][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8}
};
typedef matx[2];
matx *transpose(int matrix[][4]);
typedef maty[];
maty *transpose_generic(int nrow, int ncol, int matrix1[nrow][ncol], int matrix2[nrow][ncol]);
int main(int argc, char *argv[]) {
/* This may need a little bit of clarification. Here we want to declare a
* pointer to an array and we need the round brackets () for this. If we
* were simply to write *mat_transpose[2] we would declare an array of
* pointers since [] has higher precedence than *. */
int (*mat_transpose)[2];
int tmat[2][4];
int i;
int j;
int k;
mat_transpose = transpose(mat1);
transpose_generic(2, 4, mat2, tmat);
for (j = 0; j < 2; j++) {
for (i = 0; i < 4; i++) {
printf("mat_transpose[%d][%d] = %d\n", i, j, mat_transpose[i][j]);
printf("tmat[%d][%d] = %d\n", i, j, tmat[i][j]);
}
}
for (k = 0; k < 1; k++) {
printf("H");
}
return 0;
}
matx *transpose(int matrix[][4]) {
static int mat[4][2];
int i;
int j;
printf("Transpose a 2x4 matrix\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 4; j++) {
mat[j][i] = matrix[i][j];
}
}
return mat;
}
maty *transpose_generic(int nrow, int ncol,
int matrix1[nrow][ncol],
int matrix2[nrow][ncol]) {
int i;
int j;
printf("Transpose a matrix\n\n");
for (i = 0; i < nrow; i++) {
for (j = 0; j < ncol; j++) {
matrix2[j][i] = matrix1[i][j];
}
}
return matrix2;
}
In this line,
printf("tmat[%d][%d] = %d\n", i, j, tmat[i][j]);
When i>1 your code causes undefined behaviour since you tmat is declared as int tmat[2][4];.
The same problem exists in all three code snippets and you just happen to get segfault only for the first one. This is not at all related to whether you return a a pointer to a function scoped static variable.

Find the union of two sets of 10 digit numbers

I'm trying to find the union of two sets of 10 digit numbers, I'm passing along three int arrays: first, second, and comp (this will hold the union set).
So far, I've added first and second into one array. I was thinking about finding the matching indices in comp[] then filter through deleting them. I figure there's a much easier way. Can anyone give me a hint?
Basically I'm taking
first[] = [1,2,3,4,5,6,7,8,9,10];
second[] = [1,2,3,4,11,12,13,14,15,16];
and I want to return
comp[] = [5,6,7,8,9,10,11,12,13,14,15,16];
The numbers won't necessarily be in order.
int compound(int first[],int second[],int comp[]){
int i=0;
int indicies[20];
for(int j = 0; j<SIZE; j++){
comp[i]=first[j];
i++;
}
for(int k = 0; k<SIZE; k++){
comp[i]=second[k];
i++;
}
int z=0;
for(int l = 0; l<SIZE*2; l++){
for(int m = 0; m<SIZE*2; m++){
if(comp[l]==comp[m]){
indicies[z]=m;
z++;
}}}
return 0;
}
A first good step is (nearly) always sorting.
Sort both input-sets (unless you know they are already sorted).
Then iterate over both at once (two indices) and only add those elements to the output which fulfill your criteria (seems to be union minus intersection, thus only in one).
Bonus: The output-set will be sorted.
I suggest you start by writing a contains(int[], int) method like
#include <stdio.h>
#include <stdbool.h>
bool contains(int arr[], int val) {
int offset;
for (offset = 0; arr[offset] != '\0'; offset++) {
if (arr[offset] == val) return true;
}
return false;
}
Then your compound method could be implemented using it with something like
int compound(int first[],int second[],int comp[]){
int i=0;
int j;
for(j = 0; first[j] != '\0'; j++){
int val = first[j];
if (contains(second, val) && !contains(comp, val))
comp[i++] = val;
}
return i;
}
Finally, you can test it like
int main(int argc, char *args[]) {
int a[] = {1,2,3,'\0'};
int b[] = {2,3,4,'\0'};
int c[3];
int count = compound(a,b,c);
int i;
for (i = 0; i < count; i++) {
printf("%i\n", c[i]);
}
}
Output is
2
3
If the numeric range is small you could do this:
#include <stdio.h>
#define MAX 20 // small numeric range
#define sz(a) (sizeof(a)/sizeof(*(a)))
int xunion(int *a, int sa, int *b, int sb, int *c) {
int n[MAX] = {0};
for (int i=0; i<sa; i++) n[a[i]] = 1;
for (int i=0; i<sb; i++) n[b[i]] = 1;
int j=0;
for (int i=0; i<MAX; i++) if (n[i]) c[j++] = i;
return j;
}
void prn(int *a, int s) {
while (s-- > 0) printf("%d ", *a++);
putchar('\n');
}
int main() {
int a[] = {6, 3, 4, 7, 5};
int b[] = {2, 4, 5, 7, 6, 3};
int c[MAX];
prn(a, sz(a));
prn(b, sz(b));
int n = xunion(a, sz(a), b, sz(b), c);
prn(c, n);
return 0;
}

Resources