Understanding Data Allocation System in Statement

Viewed 50

I have been having troubles understanding the following statement:

struct term {
  int data;
  char word[200];
  };

void read_in_terms(struct term **terms, int *pnterms, char *filename);

The function takes in a pointer to a pointer to struct term, a pointer to an int, and the name of a file that is formatted like cities.txt. The function allocates memory for all the terms in the file and stores a pointer to the block in *terms. The function stores the number of terms in *pnterms. The function reads in all the terms from filename, and places them in the block pointed to by *terms.

--

I have attached a schematic to what I think this means. Essentially, in heap, we are allocating space for an "array" of struct term. and accessing like follows:

int main(void) {
    
    int terms = 2;
    int *pnterms = &terms;
    
    struct term *term_list = (struct term *)malloc(sizeof(struct term) * (*pnterms));
    
    (term_list+0)->data = 1000;
    strcpy((term_list+0)->word, "hello");
    
    (term_list+1)->data = 2000;
    strcpy((term_list+1)->word, "bye");
    
    printf("%s \n", (term_list+1)->word);
    
}

Is this right?

1 Answers

The given description is essentially correct. C passes arguments by value, while a variable in the caller scope that the called function must modify has to be passed "by reference". Since there is no "reference" type in C, that means passing a pointer to the variable.

Following is the same code rewritten to use read_in_terms instead.

#include <malloc.h>
#include <string.h>
#include <stdio.h>

struct term {
  int data;
  char word[200];
};

void read_in_terms(struct term **terms, int *pnterms)
{
    *pnterms = 2;
    *terms = malloc(sizeof(struct term) * (*pnterms));
    
    (*terms)[0].data = 1000;
    strcpy((*terms)[0].word, "hello");
    
    (*terms)[1].data = 2000;
    strcpy((*terms)[1].word, "bye");
}

int main(void) {
    
    int terms;
    struct term *term_list;

    read_in_terms(&term_list, &terms);
    
    for(int n = 0; n < terms; n++)
        printf("term[%d] data = %d, word = %s \n", n, term_list[n].data, term_list[n].word);
}

Output:

term[0] data = 1000, word = hello 
term[1] data = 2000, word = bye 
Related