C Flashcards
How do you define a const?
const int = 4;
- How do you define a typedef?
- What is the advantage of using typedef?
- typedef float dollars;
- now float and dollars are interchangable
- It makes the code more readable and it’s easy to change a number type later, it just needs to be changed in one place
- It makes the program more portable (different machines with different int values etc)
how do you use malloc?
int a[] = (int*)(malloc(sizeof(int);
struct * Node newNode = malloc(sizeof(struct * Node);
Why/When would you use a structure?
Structures are for:
- limited number of elements
- of varying type
- which need to be kept together in one place
How do you declare a structure?
How do you access a member of a structure?
struct friendStr(name of type) sarah(name of variable);
members are accessed with the ‘.’ operator
sarah.name (would give access to the value of sara’s name).
- How do you initialize a structure?
- How do you access a structure?
struct friendStr{
char name[MAXNAME];
long phoneNumber;
};
struct friendStr sarah;
scanf(“%s”, sarah.name);
scanf(“%ld”,sarah.phoneNumber);
printf(“Name is %s\n”,sarah.name);
How do you use typedef with a struct? Why would you implement this?
Two ways:
- typdef struct friendStr friend; (standalone)
- typedef struct freindStr{… } friend;(in the declaration of struct)
Implementing this reduces the ackwardness of always having to type struct friendStr friend; for each new declaration.
How do you copy the contents of one struct into another?
Easy!
struct StudentRec studA, studB;
studA = stubB;
It’s underlying library function copies all the elements from one struct into another. This is the ONLY instance this = operator works like this.
How would you take advantage of a structs ‘=’ ability to copy contents of arrays?
struct { int a[]; } a1, a2;
a1 = a2;
/* legal, since a1 and a2 are structures/*
How do you pass a struct to a function by value?
void printRecord(Student item){
…
}
int main(){
Student stundetA = {“Guass”, 99.0);
printRecord(stundentA);
return 0;
]
How do you pass a struct to a function as a pointer?
void readStudent(Stundet* s){
printf(“enter name and id”);
scanf(“%s”, (*s).lastname)
scanf(“%f”, &((*s).mark);
}
How do you parse(tokenize) a string?
char text[] = “123,abc,def”;
char * token;
token=strtok(text,”,”);
while(token != NULL){
printf(“%s\n”,token);
token=strtok(NULL,”,”);
}
How does tokenizing a string work?
It cotinues to work on the original string. It puts a terminating character at the delimiter, it then starts at the next character after the terminating character.
What are enumerations and how do you use them?
Enumerations permit the declaration of named constants in a more convenient and structured fashion than does #define; they are visible in the debugger, obey scope rules, and participate in the type system.
enum Suit{HEARTS, DIAMONDS, CLUBS, SPADES};