#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main()
{
int a = 0, len1 = 0, len2 = 0;
int BUFSIZE = 1000;
char *string1[1];
char *string2[1];
FILE *fp1 = fopen("input1.txt", "r");
FILE *fp2 = fopen("input2.txt", "r");
if ((fp1 == 0)||(fp2 == 0))
{
fprintf(stderr, "Error while opening");
return 0;
}
string1[a] = (char *)malloc(BUFSIZE);
string2[a] = (char *)malloc(BUFSIZE);
fgets(string1[0], BUFSIZE, fp1);
fgets(string2[0], BUFSIZE, fp2);
len1=strlen(string1[0]);
len2=strlen(string2[0]);
printf("%c\n", string1[0][4]);
printf("Output: \n");
srand(time(NULL));
printf("%s\n", string1[0]);
printf("%s\n", string2[0]);
printf("\n");
printf("%d %d", len1, len2);
printf("\n");
free(string1[0]);
free(string2[0]);
int x=0;
scanf("%d", &x);
fclose(fp1);
fclose(fp2);
return 0;
}
I need to read a string from a file and store it in an array. I need to read only one line of string, and each element of the array should be a character of the string. For example, if I read ‘ABCDABC’ into an array, then array[3] should be ‘D’. But I don’t really know how to do it, I modified some other’s code, and get the above code. But I don’t want to involve pointers and address stuff in my code. So could anyone tell me how to realize it without using pointers? Thank you!
Instead of
char *andmalloced memory, you can also use plainchar[N]. The changes are small, since achar[N]is automatically converted to a pointer to its first element when it is passed to a function (likjefgetsorstrlen). The code would also only minimally change if you used plainchar*forstring1andstring2,char *string1 = malloc(BUFSIZE);, the main difference here would be themallocand thefreeat the end.