I am new to coding. As a practice problem, I wrote a program to sort strings as alphabetically, as in a dictionary. My program takes as input: (a) The number of strings the user has in mind and (b) The strings, one by one, each terminated by pressing the enter key. It stores the initial input in a buffer array of size MAXSTR and simultaneously counts the number of characters. Then it creates allocates memory of requisite size at memory location input[i] and copies the buffer to that location. It also creates an index array, with array elements having value of 0, 1, 2 ... each corresponding to one the 0th string, 1st string, 2nd string ... and so on. The function dictsort sorts the index array based on the alphabetical position of the corresponding string. My program runs smoothly on Linux machines. However, on Windows, it compiles alright, but while running the executable, it ends abruptly while executing the line "input[i]=(char)malloc(jsizeof(char));". If any of you guys can indicate what is happening it will be of great help. Note that my problem is with the main function only. The sorting functions work fine, and hence those are not either included or commented out from below code.
#define MAX 10000
#define MAXSTR 100
#include<stdio.h>
#include<stdlib.h>
//int dictsort(char **mainarray, size_t *indexarray, size_t elementcount);
//int strcompare(char* str1, char* str2);
//int getvalue(int input);
int main(void){
size_t n, i, j,k;
char buffer[MAXSTR];
int c;
size_t *index;
char **input;
printf("Input number of elements:\t");
scanf("%ld", &n);
n=n<MAX ? n : MAX;
index=(size_t*)malloc(n*sizeof(size_t));
getchar(); // flush the newline after scanf
for(i=0;i<n;++i){
index[i]=i;
printf("Input element %ld:\t", i+1);
j=0;
while(((c=getchar())!=EOF) && (c!='\n') && (c!='\0') && (j<MAXSTR-1)){
buffer[j]=c;
++j;
}
buffer[j]='\0';
printf("Upto 1\n"); //program comes upto here
input[i]=(char*)malloc(j*sizeof(char));
printf("Upto 2\n"); //never reaches here
for(k=0;k<j+1;++k){
input[i][k]=buffer[k];
}
}
//dictsort(input, index, n); //disabled for debugging
printf("The sorted array is: \n");
for (i=0;i<n;++i){
printf("%s ", input[index[i]]);
}
for(i=0;i<n;++i){
free(input[i]);
}
free(index);
return 0;
}