+ 1

Help me fix this code

Objective - To create a program that uses double pointer to accept the input of a 2D array through a function and prints it in reverse order My code - #include<stdio.h> #include<string.h> #include<conio.h> int pointer_reverser(char** array); int main() { clrscr(); char arr[3][3]; printf("Please enter 9 elements to be entered in a 3 by 3 array: "); for (int i=0;i<3;i++) { for (int j=0;j<3;j++) { scanf("%c",&arr[i][j]); } } printf("Thank you for your input. Here is your reversed array: "); pointer_reverser(*arr); getch(); } int pointer_reverser(char** array) { char* ptr1 = NULL; char** ptr2 = NULL; ptr1 = array[3][3]; ptr2 = &ptr1; for (int i=0;i<3;i++) { for (int j=0;j<3;j++) { printf("%c", *ptr1); ptr1--; } ptr2 = &ptr1; } } I get a segmentation fault mid-program when compiling and running with GDB Online

5th Oct 2018, 8:33 AM
Chintan Basrani
Chintan Basrani - avatar
1 Answer
+ 1
Make note that when you decrement a pointer you get back in memory by 1*memory pointed size and because you use char**, you get back by 4 (or 8) bytes not 1 like you expected... Anymore, try this code: int pointer_reverser(char array[3][3]) { // because array is a 3x3=9 matrix and you have to point // to last element, we make the adress of last element // by adding first element address + element_count - 1 = 8 // Note that i converted array to char* for what i said before char* ptr1 = ((char*)array)+8; for (int i=0; i<3; i++) { for( int j=0; j<3; j++, ptr1-- ){ printf("%c", *ptr1); } printf("\n"); } }
5th Oct 2018, 10:08 AM
KrOW
KrOW - avatar