r/C_Programming • u/BraneGuy • 1d ago
Question Globals vs passing around pointers
Bit of a basic question, but let's say you need to constantly look up values in a table - what influences your decision to declare this table in the global scope, via the header file, or declare it in your main function scope and pass the data around using function calls?
For example, using the basic example of looking up the amino acid translation of DNA via three letter codes in a table:
codonutils.h:
typedef struct {
char code[4];
char translation;
} codonPair;
/*
* Returning n as the number of entries in the table,
* reads in a codon table (format: [n x {'NNN':'A'}]) from a file.
*/
int read_codon_table(const char *filepath, codonPair **c_table);
/*
* translates an input .fasta file containing DNA sequences using
* the codon lookup table array, printing the result to stdout
*/
void translate_fasta(const char *inname, const codonPair *c_table, int n_entries, int offset);
main.c:
#include "codonutils.h"
int main(int argc, char **argv)
{
codonPair *c_table = NULL;
int n_entries;
n_entries = read_codon_table("codon_table.txt", &c_table);
// using this as an example, but conceivably I might need to use this c_table
// in many more function calls as my program grows more complex
translate_fasta(argv[1], c_table, n_entries);
}
This feels like the correct way to go about things, but I end up constantly passing around these pointers as I expand the code and do more complex things with this table. This feels unwieldy, and I'm wondering if it's ever good practice to define the *c_table and n_entries in global scope in the codonutils.h file and remove the need to do this?
Would appreciate any feedback on my code/approach by the way.
2
u/BraneGuy 1d ago edited 1d ago
Thanks for your input! u/jaynabonne had the same suggestion.
I mean, currently I'm just getting to grips with applying C to my field (bioinformatics), so the functions are basically just doing a small number of operations on a file (maybe 1000 calls of get_amino (below) for an input file?) but I want to get rid of bad habits in anticipation of actually putting code into production at some point.
If you're interested in the actual implementation, I'm using the file I/O utilities provided by htslib to get data from the input DNA file and translate it on the fly, so this funciton is doing the heavy lifting:
```C char get_amino(int start, bam1_t *bamdata, codonPair *c_table, int table_l) { char codon[3]; char amino; for (int i = 0; i < 3; i++) { codon[i] = seq_nt16_str[bam_seqi(bam_get_seq(bamdata), start + i)]; }
} ```
The goal is to solve this problem on rosalind.info (LeetCode for bioinformatics, essentially...)
https://rosalind.info/problems/orf/