I am trying to learn C. I want to fill a 2D array from a 1D array that I have got from a File.
Now, I am trying to take the elements of array pointer that outputs (Hello,My,name,is,Ram.) into a 2D array called words. the purpose is to remove commas and highlight each word in a different row. I have achieved that too However I am getting some gibberish along with my output. I have checked my entries one by one and found that the first line(Hello,My,name,is,Ram.) is stored in from row 1 to 5 in words[][]. the values contained in words[][] between row 5 to 10 is gibberish. However, the next line(I,own,20,thousand,bucks.) starts at row [10] of word that I don't understand why? plus my output looks weird with some unknown values. Please inform me what should I do to correct my output and size the 2 D array equal to the value it contains
Here's my code:
int main(int argc, const char * argv[]) {
FILE *fp;
char (*points)[50];
char *array;
int width=20,height=50;
char *word;
char words [width][height];
int counter=0;
points = malloc(sizeof(*points) * 2);
word=malloc(width*height*sizeof(char));
if (points == NULL) {
perror("malloc");
exit(0);
}
fp = fopen("/Users/shubhamsharma/Desktop/data.txt", "r");
if (fp == NULL) {
perror("fopen");
exit(EXIT_FAILURE);
}
fgets(points[0], sizeof(*points), fp);
fgets(points[1], sizeof(*points), fp);
array=points[0];
printf("%s", points[0]);
printf("%s", points[1]);
for(int i=0;i<width;i++)
{
for(int j=0,p=counter;j<height;j++,p++)
{
if(array[p]==','||array[p]=='\0')
{
words[i][j]='\n';
counter=++p;
break;
}
else
words[i][j]=array[p];
}}
printf("\n%c",words[16][0]);
for (int i=0; i<width; i++) {
for (int j=0; j<height; j++) {
if(words[i][j]=='\n')
{
break;
}
printf("\nPrinting element in word\n");
printf("%c",words[i][j]);
}
}
printf("\n");
fclose(fp);
free(points);
return 0;
return 0;
}
Output:
Hello,My,name,is,Ram. I,own,20,thousand,bucks. Printing element in word
HelloMynameisRam.+̮\213\377\310`\267t\377̮\213\377Iown20thousandbucks.
Program ended with exit code: 0
Lines in my file looks something like.-
Hello,My,name,is,Ram.
I,own,20,thousand,bucks.