0

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);
}
2
  • 4
    a char[n][m] is not synonymous with char**. Whatever tutorial or book said otherwise... burn it. Commented Nov 7, 2018 at 15:56
  • This is pretty unsafe. You've made a 2d array of char, and then you call scanf on a string. This is asking for segfault overruns. And As Whoz said, char[][] is not char**. Commented Nov 7, 2018 at 16:05

2 Answers 2

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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;
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.