Passing a 2d array with pointers and accessing it gives segmentation fault - c

im trying to pass a 2D array from main to a function and trying to print it letter by letter
but it keeps giving me segmentation fault
note: the question im trying to solve as mentioned a function with parameter { ArrPrintMatrix(char *(p)[7]) }
so help me by keeping the above thing in mind
#include<stdio.h>
ArrPrintMatrix(char **p,int n) {
int i,j;
for(i=0;i<n;i++) {
for(j=0;j<10;j++) {
printf("%c ",p[i][j]);
}
}
}
main() {
int i;
char c[2][10];
puts("enter two strings");
for(i=0;i<2;i++)
scanf("%s",c[i]);
ArrPrintMatrix((char **) c,2);
}

You should use char p[2][10] not char** p
The following code could work:
#include <stdio.h>
void ArrPrintMatrix(char p[2][10], int n) {
int i;
for (i = 0; i < n; ++i)
printf("%s\n",p[i]);
}
int main() {
int i;
char c[2][10];
puts("enter two strings");
for(i=0;i<2;i++)
scanf("%s",c[i]);
ArrPrintMatrix(c,2);
return 0;
}

you need to change the type of the p var in the print function, and you should also set the array to zero so if the strings that are printing are less than 10 chars with terminator- garbage values are not displayed.
void ArrPrintMatrix(char p[][10],int n) {
int i,j;
for(i=0;i<n;i++) {
for(j=0;j<10;j++) {
printf("%c ",p[i][j]);
}
}
}
int main() {
int i;
char c[2][10]= {0};
puts("enter two strings");
for(i=0;i<2;i++)
scanf("%s",c[i]);
ArrPrintMatrix( c,2);
return 0;
}

Related

I wrote a function to sort a string in alphabetical order but getting a segmentation fault

sort and swap functions take pointer as argument, when I try it with 2 or 3 strings it works fine but for more than three its giving a segmentation fault, this is my code please let me know what's going on here and why it's giving this error.
#include <stdio.h>
#include <string.h>
void get(int r, int c, char (*s)[c]);
void print(int r, int c, char (*s)[c]);
void sort(int r, int c, char (*s)[c]);
void swap(int c, char (*s)[c], char (*s1)[c]);
void main()
{
int r;
printf("\n\t enter no. : ");
scanf("%d", &r);
char s[r][31];
get(r,31,s);
sort(r,31,s);
printf("\n\tsorted list");
print(r,31,s);
}
void get(int r, int c, char (*s)[c])
{
int i, j;
for(i = 0; i < r; i++)
{
printf("\n\t");
scanf("%s", *(s+i));
}
}
void print(int r, int c, char (*s)[c])
{
int i, j;
for(i = 0; i < r; i++)
{
printf("\n\t%s", *(s+i));
}
}
void sort(int r, int c, char (*s)[c])
{
int i, j, k;
for(i = 0; i < r; i++)
{
for(j = 0, k = 1; j < r-1; j++, k++)
{
if(strcmp(*(s+j),*(s+k)) > 0)
{
swap(c, (s+j), (s+k));
}
}
}
}
void swap(int c, char (*s)[c], char (*s1)[c])
{
char (*t)[c];
strcpy(*t, *s);
strcpy(*s,*s1);
strcpy(*s1,*t);
}
t is a pointer and as such it needs to be initialized, that is the reason for the segmentation fault, you need to allocate and assign the needed memory though a way better solution would be to simply make it an array:
void swap(int c, char (*s)[c], char (*s1)[c])
{
char t[c];
strcpy(t, *s);
strcpy(*s,*s1);
strcpy(*s1,t);
}
Or
char (*t)[c] = malloc(sizeof *t); // you'll need stdlib.h
With this second option you must free the memory:
free(t);
I would strongly advise the first solution though.
I would also strongly advise the use of a width limiter for the scanf in your get function, otherwise you are at risk of buffer overflow and consequently of undefined behavior.
scanf("%30s", *(s+i));
// discard extra characters in case the input is larger than the destination buffer
while ((c = getchar()) != '\n' && c != EOF){}
Note that main return type should be int.
Live sample

using pointer subscript inside an array

i wrote a program for counting sort using pointers
#include<stdio.h>
#include<stdlib.h>
int max(int *arr,int n)
{
int i;
int maxi=*arr;
for(i=0;i<n;i++)
{
if(*(arr+i)>maxi)
maxi=*(arr+i);
}
return maxi;
}
void count(int *arr,int n)
{
int i;
int s=max(arr,n);
printf("max %d",s);
int c[s];
memset(c,0,s*sizeof(int));
int b[n];
for(i=0;i<n;++i)
{
++c[arr[i]];
}
for(i=1;i<s;++i)
{
c[i]=c[i]+c[i-1];
}
for(i=n-1;i>=0;--i)
{
b[c[arr[i]]]=arr[i];
--c[arr[i]];
}
for(i=0;i<n;++i)
{
arr[i]=b[i];
}
}
void print(int *arr,int n)
{
int i;
for(i=0;i<n;i++)
printf("\nelement is %d ",*(arr+i));
}
int main()
{
int n,i;
int *arr=malloc(n*sizeof(int));
printf("\nenter the number of elements ");
scanf("%d ",&n);
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
count(arr,n);
print(arr,n);
return 0;
}
as i debug the program it stops at ++c[arr[i]] giving a segmentation fault. My call watches window looks like this
my inputs were like this
enter the number of elements 4
1
3
5
7
max 7
the code received segmentation fault after this also, the value of i is initialized to 0,then why is the watches window showing it's value as 4. is it fine to pass pointer subscripts to a static array or should i declare c dynamically?

Inserting one element in the right position in a sorted array using binary search to find the right position,,,but having a run time error

this is my code
#include <stdio.h>
void show(int*,int);
int sort (int*,int);
int BinSearch(int[],int,int);
int Insertelem(int*,int,int,int*);
int main(void)
{
int array[100]={15,30,40,10,25,5,35,20,45};
int len=9;//length
int *pos=0;//position
int elem=0;//element
int ok=0;
printf("array : ");
show(array,len);
sort(array,len);
printf("array after sorting : ");
show(array,len);
printf("enter the number you want to add :");
scanf("%d",&elem);
*pos=BinSearch(array,elem,len);
ok=Insertelem(array,len,elem,pos);
show(array,len);
return 0;
}
void show(int *array,int len)//print the array
{
for(int i=0;i<len;i++)
{
printf("%d,",array[i]);
}
printf("\n");
}
int sort(int *array,int len)//sort the array
{
int help=0;
for(int i=len-1;i>0;i--)
{
for(int j=0;j<i;j++)
{
if(array[j]>array[j+1])
{
help=array[j];
array[j]=array[j+1];
array[j+1]=help;
}
}
}
return *array;
}
int BinSearch(int array[100],int elem,int len)//searching for the position
{
int first=1;
int last=len-1;
int middle=(first+last)/2;
int pos;
while(first<=last)
{
if(elem<array[middle])
{
last=middle-1;
middle=(first+last)/2;
}
else if(elem>array[middle])
{
first=middle+1;
middle=(first+last)/2;
}
else if(elem==array[middle])
{
break;
}
}
pos=array[middle]+1;
return pos;
}
int Insertelem(int *array,int len,int elem,int *pos)//inserting the element
//in the right position
{
len++;
for(int i=len-1;i>*pos+1;i--)
{
array[i+1]=array[i];
}
elem=array[*pos];
return *array;
}
note : there is no compiler error
I think the problem is in the binsearch function or Insertelem function because I tested all other functions and they are working as expected
when I run this code it works so good until the user enter the element he wont and the program just crash
int pos=-1;//change not pointer
...
pos=BinSearch(array,elem,len);
ok=Insertelem(array,len,elem,&pos);//pos is no need for a pointer, because since not changed.
len += 1;//The length must be changed(or by inside Insertelem)
...
int BinSearch(int array[100],int elem,int len)//searching for the position
{
int first=0;//not 1
...
pos=first;//not midlle, not element of array(array[middle])
return pos;
}
int Insertelem(int *array,int len,int elem,int *pos)
{
...
for(int i=len-1;i>= *pos;i--)//not i>*pos+1
...
array[*pos]=elem;//not elem=array[*pos];
return *array;//??
}

Error while printing sorted float array

Write a program which should get 5 floating values from the user in an array using a function insert and then sort these values using a function sort after that print the sorted values on the screen using a function disp.
This is my code please tell me where i have done something wrong.It prints 0.000 after sorting.
#include <stdio.h>
void insert(float array[],int val);
void disp(float array[],int val);
void sort(float array[], int val);
void main ()
{
float array[5],j;
printf("Enter numbers: \n");
insert(array,5); //array input function
printf("Enter numbers are: \n");
disp(array,5); //array output function
sort(array,5); //array sort function
printf("\nSorted Array is: \n");
disp(array,5); //array output function
}
//array input function
void insert(float array[],int val)
{
int k,i;
for (k = 0;k<5;k++){
scanf("%f",&array[k]);
}
}
//array sort function
void sort(float array[], int val){
int i,j;
float hold;
for(i=0; i<6; i++)
{
for(j=0; j<6; j++)
{
if(array[j]>array[j+1])
{
hold=array[j];
array[j]=array[j+1];
array[j+1]=hold;
}
}
}
}
//array display function
void disp(float array[],int val)
{
int k;
for (k = 0;k<5;k++){
printf("%f\n",array[k]);
}
}
Sort function should look like this:
//array sort function
void sort(float array[], int val)
{
int i,j;
float hold;
for(i=0; i<4; i++)
{
for(j=0; j<4; j++)
{
if(array[j]>array[j+1])
{
hold=array[j];
array[j]=array[j+1];
array[j+1]=hold;
}
}
}
}
In the original code first loop executes two times too many.
Second loop causes reading beyond the array. Since you have 5 elements you need 4 comparisons.
First of all, you declared some variables that you didn't use, especially int val in your functions.
Secondly, you don't need to implement a function to insert values in an array, just loop it with a scanf directly.

array within a structure in c

This is my code. main should have only calling function. testcases() call the test cases run through the program.
#include<stdio.h>
#include"conio.h"
int main()
{
testcases();
}
struct test {
int a[10];
} testDB[5] = {
{1,2,3,4,5,6},
{7,8,9,0,1,2,3,4}
};
void testcases()
{
int i;
for(i=0;i<2;i++)
displaytest(testDB[i].a);
}
displaytest(char *a)
{
int i=0;
while(a[i]!='\0')
{
printf("%d\n",a[i]);
i++;
}
}
I want to display both the arrays. But I am getting only first indexes.
Can anyone help ?
Your passed parameter is not appropriate;
displaytest(char *a) --> void displaytest(int *a)
EDIT: Your while loop won't work, as stated in the first comment.
You can not check like this while(a[i]!='\0')
You have to pass the size of the array as 2nd parameter.
void displaytest(int *a, int size)
{
int i = 0;
while (i < size/sizeof(int))
{
printf("%d\n", a[i]);
i++;
}
}
While calling, you can call like this...
displaytest(testDB[i].a, sizeof(testDB[i].a));

Resources