I've been working with pointers a bit, and I've made the following:
Code:
#include <stdio.h>
struct structurevariable{
char a[20];
};
int main()
{
int count;
struct structurevariable * var[2]; //An array of 2 strucure pointers is created.
for (count = 0; count < 2; count++)
{
/* The size of var[count] is determined. First a typecast is done to let
malloc return a pointer-variable of the type "structurevariable". Then malloc
allocates room for one structure with the size of one "structurevariable." */
var[count]=(struct structurevariable*)malloc(sizeof(struct structurevariable));
puts("Enter data: ");
/* Dot operator requires a variable name. Here -> is used for pointers. */
scanf(" %s", var[count]->a); //Will store whatever var[count] points to, in a.
printf("You entered: %s\n", var[count]->a);
free(var); //Gives the memory taken by: var[count] back to the system.
}
getchar();
getchar();
return 0;
}
I've made comments, so that I can understand later more easily how it works.
I've got a couple of questions about this:
1. Shouldn't I include the stdlib.h? I noticed I could get away with not including it.
2.
Code:
var[count]=(struct structurevariable*)malloc(sizeof(struct structurevariable));
Why is in sizeof(struct structurevariable) the "struct" neccesary? I thought I had created a new data type with the name structurevariable (like int or char).
3. Am I correct when I say that: var[count] will only contain a memoryadress of the users input? If yes, where will the actual input be stored ( I would think in *var[count])?
4. Why is the code for storing the variables and printing them to screen the same? I'd assume that I'd have to dereference something to gain a value.
Thank You,
OmnificienT