Quote:
>Hello.
>I wrote the following program as an exercise in Kernighan and
>Ritchie's book, but I was wondering whether someone could tell me the
>simplest way of replacing the two malloc statements with one calloc
>statement.
What do you want to achieve using that? malloc and calloc are very similar,
the only real difference between them is that calloc set the allocated memory
to all-bits-zero. True, calloc takes two arguments but that doesn't increase
its functionality, you can allocate the same space by calling malloc with
the product of the arguments passed to calloc.
Quote:
>#include <stdio.h>
>#include <stdlib.h>
>#include <string.h>
>/* compare two files */
>main(int argc, char *argv[])
>{
>char *line = (char *) malloc(100*sizeof(char));
>char *line1 = (char *) malloc(100*sizeof(char));
You could convert these into one allocation like so:
char *line = malloc(2*100);
char *line1 = line+100;
If you insist on unsing calloc you might try:
char *line = calloc(2, 100);
char *line1 = line+100;
Note that this technique won't work in general if the objects you are
allocating have different types, you need to ensure that alignment is
correct for the second object. That isn't a problem in this case however.
Quote:
>FILE *fp, *fp1;
>int n = 100;
> if (argc != 3)
> printf("usage: 7.6 file1 file2\n");
> else {
> if ((fp = fopen(argv[1], "r")) == NULL)
> {
> fprintf(stderr, "can't open %s\n", argv[1]);
> exit(1);
1 doesn't necessarily indicate failure. The portable way to indicate that
is to use:
exit(EXIT_FAILURE);
Quote:
> }
> else
> fp1 = fopen(argv[2], "r");
> while (fgets(line, n, fp) != NULL)
> {
> fgets(line1, n, fp1);
> if (strcmp(line1, line) == 0)
> continue;
> else
> {
> printf("Files differ at the
> following line of the second file: %s\n",
>line1);
> exit(1);
> }
> }
> }
You really should tidy up allocated memory where possible:
free(line);
Quote:
>fclose(fp);
>fclose(fp1);
>}
--
-----------------------------------------
-----------------------------------------