svata:
Hello Frederick,
Hello svata :)
I know it doesn't make sense. I was wrong in my assumption.
I should use p_structure = (STRUCTURE **) malloc(FIRST *
sizeof(STRUCTUR E*));
but anyway... should rather use array of structures.
typedef structure {
code goes here...
} _structure;
_structure *p_structure;
One thing that you'll notice as you program more and more is that you'll
come to use abbreviations (most programmers do in anyway). Humans love
shortcuts. "should have" became "should've" , which became "shuda". The
words "until" and "because" are slowly but surely becoming "til" and
"cause".
When I myself define a pointer variable, I simply prefix "p" to the name; I
used to put an underscore with it too but then more months passed by and I
got lazier and lazier. The variable name "p_structur e" is a bit of a
mouthful, maybe you'd prefer to keep the names small.
There are a few different prevalent coding styles out there. My own style
works as follows:
(1) Functions and Types start with a capital letter. If it consists of more
than one word, than the next word starts with an initial capital, e.g.
void TruncateLastFiv eDigits(char*);
(2) Objects start with a lower case letter. If it consists of more than one
word, then underscores are used, e.g.
int len_main_str = 34;
(3) For a pointer, I prefix a simple "p" to the name where possible:
void (*pFunc)(int) = Func;
void (**ppFunc)(int) = &pFunc;
int *pobj = &obj;
int **ppobj = &pobj;
int ***pppobj = &ppobj;
(4) Macro names are in ALL CAPS. No other name should be written in ALL
CAPS, e.g.:
#define LEN 5
#define SQR(x) ((x)*(x))
Of course, this is just my own style. I'm not trying to shove it down your
throat, but I'm just suggesting it as I thought you might like it.
// and then malloc()
p_structure = malloc( INT * sizeof(_structu re));
if am I right?
Yes, you're right. It's handy though to not have to repeat the name of the
type:
int *const p = malloc(5 * sizeof(int));
can be written as:
int *const p = malloc(5 * sizeof*p);
Now, if we change the type to double, we only have to change "p":
double *const p = malloc(5 * sizeof*p);
Here's a taste of how I might write the code:
#include <stddef.h /* To use "size_t" */
#include <stdlib.h /* To use "malloc" and "free" */
typedef struct MyStruct {
int i;
} MyStruct;
size_t GetNumberFromSo mewhere(void); /* Defined elsewhere */
int main(void)
{
size_t const len = GetNumberFromSo mewhere();
MyStruct *const p = malloc(len * sizeof*p);
/* ... */
free(p);
return 0;
}
--
Frederick Gotham