I am a beginner in programming. What is a segmentation fault and how to remove that on the following program?
The following is a compare the triplets problem asked in hackerrank. I receive a segmentation fault when attempting to run the program.
int main() {
int a, b, c;
c = points(a, b);
printf("%d", c);
return 0;
}
int points(int a[10], int b[10]) {
int p = 0, q = 0;
for (int i = 0; i < 3; i++) {
printf("%d", a[i]);
scanf("%d", & a[i]);
}
for (int j = 0; j < 3; j++) {
printf("%d", b[j]);
scanf("%d", & b[j]);
}
for (int k = 0; k < 3; k++) {
if (a[k] > b[k]) {
++p;
return p;
} else {
if (a[k] = b[k])
++q;
return q;
}
}
return 0;
}
int a,b,c;
c=points(a,b);
You are passing arguments to function without setting theirs value. Remember that in C, you are passing arguments to function by value.
int points(int a[10],int b[10])
This function expects two arrays of ten integers. You are passing only one integer for each.
You should also read about passing array arguments to function (if that was your intention). In C, You can't pass whole array to function unless it is wraped into a struct. You should only pass address of the first array element and in some way define size. For example:
#define ARRAY_SIZE 10
int foo(int tab[])
{
int i;
for (i = 0; i < ARRAY_SIZE; i++)
tab[i] = do_stuff();
}
int main(void)
{
int tab[ARRAY_SIZE];
foo(tab);
}
You can also not define ARRAY_SIZE macro, but pass another argument to a function which will define the size of passed array.
Related
This question already has answers here:
Passing an array as an argument to a function in C
(11 answers)
Closed 2 years ago.
I am learning C and I am confused why the matrix in main changes in the function change. I am assuming that the matrix was passed in the function change as ma[10][10] and that matrix m shouldn't change because I declared it in main, right? Can someone explain what is happening in this case? How do I fix it?
thx for help
void change(int ma[2][3]){
int l, c;
for(l=0; l<2; l++){
for(c=0; c<3; c++){
ma[l][c]=1;
}
}
}
int main()
{
int m[2][3], l, c;
for(l=0; l<2; l++){
for(c=0; c<3; c++){
m[l][c]=0;
}
}
change(m);
for(l=0; l<2; l++){
for(c=0; c<3; c++){
printf("%d", m[l][c]);
}
printf("\n");
}
return 0;
}
I was expecting to see this:
000
000
What i get:
111
111
void change(int ma[2][3]){ ...
......
int m[2][3];
change(m);
"Why does the matrix in main change?"
You pass the array m by reference to the function change.
The parameter int ma[2][3] is in fact not an array, it is a pointer of type int (*)[3] and will point to the address of the first element of m in main().
That is why m in main got changed.
"How do I fix it?"
C does not allow to pass or return arrays by value to or from functions.
However, there are workarounds. You can f.e. wrap the array into a structure and then access the array inside of the structure. The structure you can pass and return by value.
#include <stdio.h>
#define ROWS 2
#define COLS 3
struct x {
int m[ROWS][COLS];
};
static void no_change (struct x b)
{
int l, c;
for ( l = 0; l < ROWS; l++) {
for ( c = 0; c < COLS; c++ ) {
b.m[l][c] = 1;
}
}
}
int main (void)
{
int l, c;
struct x a;
for ( l = 0; l < ROWS; l++ ) {
for ( c = 0; c < COLS; c++ ) {
a.m[l][c] = 0;
}
}
no_change(a);
for ( l = 0; l < ROWS; l++ ) {
for ( c = 0; c < COLS; c++ ) {
printf("%d", a.m[l][c]);
}
printf("\n");
}
return 0;
}
Output:
000
000
Because the arrays are passed by the pointer not the value.
So you work on the same array.
In C only scalar types, structs and unions are passed by value
How can I fix it?
You can't fix it. If you really want to pass the array by value, you need to wrap it into the struct
typedef struct
{
int arr[2][3]
}ARR_WRAP;
void change(ARR_WRAP ma)
{
int l, c;
for(l=0; l<2; l++)
{
for(c=0; c<3; c++)
{
ma.arr[l][c]=1;
}
}
}
int main()
{
ARR_WRAP m;
for(int l=0; l<2; l++)
{
for(int c=0; c<3; c++)
{
m.arr[l][c]=0;
}
}
change(m);
for(int l=0; l<2; l++)
{
for(int c=0; c<3; c++)
{
printf("%d", m.arr[l][c]);
}
printf("\n");
}
return 0;
}
I am trying to input a matrix of order p*q using a function I got some errors. how to get the input using a pointer it gives me a segmentation fault .
#include<stdio.h>
int read_matrix(int *x,int p,int q){
for(int i=0;i<p;i++){
for(int j=0;j<q;j++){
scanf("%d",*(x+i)+j);
}
}
return 0;
}
int main(){
int p,q;
printf("enter the order of the matrix");
scanf("%d%d",&p,&q);
int a[p][q];
read_matrix(a[q],p,q);
for(int i=0;i<p;i++){
for(int j=0;j<q;j++)
printf("%d",a[i][j]);
}
}
You have multiple problems and seem to misunderstand how arrays and pointers work. To begin with a[q] will be out of bounds if p <= q.
a[q] (if q is valid) is an array of q elements, which decays to a pointer to its first element. It's not any kind of pointer to the matrix itself.
And inside the read_matrix function when you do *(x + i) + j that is actually equal to x[i] + j which is a single int value, and not a pointer to an element in any array.
You need to pass the matrix itself to the function, and let it decay to a pointer to an array, and use that as a proper "array of arrays":
// Use variable-length arrays for the matrix argument x
// Declare it as a pointer to an array of q integer elements
// Note the changed order of arguments, it's needed because q must be declared
// before its used for the VLA
void read_matrix(int p, int q, int (*x)[q]) {
for (int i = 0; i < p; ++i) {
for (int j = 0; j < q; ++j) {
scanf("%d", &x[i][j]); // Use normal array indexing and address-of operator
}
}
}
int main(void) {
int p, q;
scanf("%d %d", &p, &q);
int a[p][q];
// Here a will decay to a pointer to its first element, &a[0]
// Since a[0] is an array of q elements, the type will be
// int (*)[q], exactly as expected by the function
read_matrix(p, q, a);
for (int i = 0; i < p; ++i) {
for (int j = 0; j < q; ++j) {
printf("%d ", x[i][j]);
}
printf("\n");
}
}
You are making things needlessly complicated with the pointer arithmetic. *(x+i)+j means x[i] + j*sizeof(int) which is not what you want.
Just do something like this instead:
#include<stdio.h>
void read_matrix(int x, int y, int matrix[x][y])
{
int count=0;
for(int i=0;i<x;i++)
for(int j=0;j<y;j++)
matrix[i][j] = ++count;
}
int main (void)
{
int x=3, y=2;
int matrix[x][y];
read_matrix(x,y,matrix);
for(int i=0;i<x;i++)
{
for(int j=0;j<y;j++)
printf("%d ",matrix[i][j]);
printf("\n");
}
}
I am trying to write a C function to add two arrays. The function should work with any array sizes and it should receive a reference to both arrays and the number of rows and the number of columns and it should return a pointer to the first element of the resulting array.
How would I do that? When I try to pass a two dimensional array to a function I get an error?
#include<stdio.h>
void function(int r, int c,int a[][]){
int i,j;
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d, ",a[i][j]);
}
printf("\n");
}
}
int main(){
int array[2][2] = {{1,2},{4,5}};
function(2,2,array);
return 0;
}
Assuming C99, or C11 with an implementation that doesn't define __STDC_NO_VLA__, you could use the variable length array (VLA) notation and could write:
void function(int r, int c, int a[r][c])
{
for (int i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
printf("%d, ", a[i][j]);
putchar('\n');
}
}
Or something equivalent to that. The dimensions must be defined before they're used in the array specification.
If you don't have access to even a C99 compiler but only a C90 compiler, then you have to pass a pointer to the first element of the array and the sizes and you perform the array index calculation explicitly.
void function(int r, int c, int *a)
{
for (int i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
printf("%d, ", a[i * c + j]);
putchar('\n');
}
}
Now you call the function like this:
int main(void)
{
int array[2][2] = { { 1, 2 }, { 4, 5 } };
function(2, 2, &array[0][0]);
return 0;
}
The code works fine I'm just worried about the warning messages I'm getting, would there be a way to make them not appear? Is there any reason to be worried about them? Also farther down in the code I don't quite understand what I did or why it worked. It wasn't working before so I looked up what other people did with pointers and it works now
Warning passing argument 1 of 'readarray' from incompatible pointer type [-wincomp
readarray(&a);
^
note: expected 'int*' but argument is of type 'int(*)[10]'
void readarray (int*);
^
This is the warning message, I get it for each of my functions^^^^^^^^^^^^^^^^^^
I understand why it's having issues, I think, but I don't understand how I could change anything
#include <stdio.h>
#define n 10
void readarray (int*);
int findmaxvalue(int*);
void reversearray(int*, int*);
void printarray(int*);
int main(void)
{
int a[n], i, b[n];
for (i = 0; i < n; i++)
{
a[i] = 0;
}
for (i = 0; i < n; i++)
{
b[i] = 0;
}
readarray(&a);
findmaxvalue(&a);
reversearray(&a, &b);
printarray(&b);
return 0;
}
void readarray (int *a)
{
int *q;
q = a;
printf("Enter up to 10 numbers. Terminate by entering a 0\n");
Right here, why can't I use 'a' instead of 'a+n'
for(q = a; q < a+n; q++)
{
scanf("%d", q);
if (*q == 0)
break;
}
printf("\n");
}
int findmaxvalue(int *a)
{
int i, max;
max = a[0];
for (i = 1; i < n; i++)
{
if (a[i] > max)
max = a[i];
}
printf("The highest element in the array is: %d\n\n", max);
return max;
}
void reversearray(int *a, int *b)
{
int *i, *j, t;
for (i = a; i < a+n; i++)
{
for (j = i + 1; j < a+n; j++)
{
if (*j < *i)
{
t = *j;
*j = *i;
*i = t;
}
}
}
for (i = a + n - 1, j = b; i > a; i--, j++)
{
*j = *i;
}
}
void printarray(int *b)
{
int *q;
q = b;
printf("The reversed array in descending order is:\n");
for (q = b; q < b+n; q++)
{
printf("%d ", *q);
}
}
I think the error message is pretty self-describing.
In your code, a is an array type, having int [10]. You pass &a, which is of type pointer to an array of 10 ints, or, int (*)[10] which is not the same type as a pointer to int, i.e., int *. Hence the compiler screams.
As array type variables decay to the pointer to the first element of the array while passed as function arguments, you should call your function like
readarray(a);
I need to create a function that takes a matrix and returns it transpose. The only requirement is that it directly returns a matrix, not just modifies it by reference. Here's what I've done so far:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define ROW 100000000
#define COL 100000000
int (*(f_MatTrans)(int mat[][COL], int r, int c))[COL];
int main(void)
{
int x[2][2]={1,2,3,4};
int (*a)[2];
a=f_MatTrans(x,2,2);
for(int i=0; i<2; i++)
{
for(int j=0; j<2; j++)
{
printf("X[%d][%d]=%d\n",i,j,x[i][j]);
printf("A[%d][%d]=%d\n",i,j,a[i][j]);
}
}
return 0;
}
int (*(f_MatTrans)(int mat[][COL], int r, int c))[COL]
{
int a[c][r];
for(int i=0; i<r; i++)
{
for(int j=0; j<c; j++)
{
a[j][i]=mat[i][j];
}
}
return a;
}
The purpose of this is to include the function on a library created by myself, just in case it is useful information.
The code in the question (when I read it) doesn't compile because the array x is not compatible with the function signature.
I'm not clear what the real constraints on your problem are. The easy way to do it in C99 or C11 is with VLA notation:
#include <stdio.h>
static void MatrixTranspose(int r, int c, int src[r][c], int dst[c][r])
{
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++)
dst[j][i] = src[i][j];
}
int main(void)
{
int x[3][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 } };
int y[2][3];
MatrixTranspose(3, 2, x, y);
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
{
printf("X[%d][%d]=%d ", i, j, x[i][j]);
printf("Y[%d][%d]=%d\n", j, i, y[j][i]);
}
}
return 0;
}
Sample output:
X[0][0]=0 Y[0][0]=0
X[0][1]=1 Y[1][0]=1
X[1][0]=2 Y[0][1]=2
X[1][1]=3 Y[1][1]=3
X[2][0]=4 Y[0][2]=4
X[2][1]=5 Y[1][2]=5
My suspicion is that you are supposed to be doing something different (notationally more complex), but it is not yet clear what.
You cannot return a pointer to the local array, because that ceases to exist when the function returns. If you want your function to create the result array (not write to some other array that is passed into the function), you must use malloc() in these cases:
//The return type is actually `int (*)[r]`, but C doesn't like that.
int* f_MatTrans(int r, int c, int mat[][c]) {
int (*a)[r] = malloc(c*sizeof(*a));
for(int i=0; i<r; i++) {
for(int j=0; j<c; j++) {
a[j][i]=mat[i][j];
}
}
return *a;
}
Note that I changed the array types: If you declare mat as int mat[][COL], the number COL will be used to calculate the offset mat[1][0], which will be 100000000 integers after the first element in your case, while the array that you pass in only contains four integers. This is undefined behavior, and your program is allowed to format your harddrive if you do this.
Unfortunately, it is not possible for the type of the returned pointer to depend on the value of an argument to the function. That is why I changed the return type to a plain integer pointer, you must document that this is meant to be a pointer of type int (*)[r].
You would use the function above like this:
int main(void) {
int x[2][3]={1,2,3,4,5,6};
int (*a)[2] = (int (*)[2])f_MatTrans(2, 3, x);
for(int i=0; i<2; i++) {
for(int j=0; j<2; j++) {
printf("X[%d][%d]=%d\n",i,j,x[i][j]);
printf("A[%d][%d]=%d\n",i,j,a[i][j]);
}
}
free(a); //Cleanup!
return 0;
}