c - How to allocate the 2d array of pointers using arguments of main function -
write c program take 2 integers arguments. program should allocate 2d array of characters dynamically, read data, print them, , free array. array dimensions of array taken main arguments. problem in code run , input correct output isn't correct run time error output
int main (int y,char *x[]){ int i,j,v,b; v=atoi(x[1]); b=atoi(x[2]); char*m[v]; for(i=0;i<v;i++) m[i]=(char*)malloc(b*sizeof(char)); for(i=0;i<v;i++) for(j=0;j<b;j++) scanf("%s",&m[i][j]); for(i=0;i<v;i++){ for(j=0;j<b;j++) printf("%s",m[i][j]); } return 0; }
#include <stdio.h> #include <stdlib.h> #include <string.h> int main (int y,char *x[]){ int i,j,v,b; v=atoi(x[1]); b=atoi(x[2]); char *m[v][b];//allocate 2d array of pointers on stack for(i=0;i<v;i++){ for(j=0;j<b;j++){ char buff[128]; scanf("%127s", buff); m[i][j] = malloc(strlen(buff)+1); strcpy(m[i][j], buff); } } for(i=0;i<v;i++){ for(j=0;j<b;j++){ printf("%s ", m[i][j]); free(m[i][j]); } printf("\n"); } return 0; }
Comments
Post a Comment