SCC111: weeks 6-10 Flashcards
(30 cards)
how are strings handled in C?
-just an array of strings
-need a terminating character: \0
–(doesn’t need to be explicitly added to a string)
how would you create a string ‘hello’ in C?
char *string = “hello”;
or
char string[] = “hello”;
what is the library the provides many string functions?
<string.h>
</string.h>
what is the size of a char?
8-bit integers
if two variables:
char* stringval = “hi”;
char* stringval2 = “hi”;
are compared: stringval == stringval2
will it compute?
-won’t work
-instead use <string.h> function strcmp()
returns (-1,0 or 1)</string.h>
int equal = strcmp(stringval,stringval2);
list some other useful methods in <string.h></string.h>
-int strlen(char)
-char strchr(char, int) (find character within a string, returns pointer)
-strcat(char d,char* s) (append string s to d)
-strcpy(char* d, char* s) (copy string s to d)
what are we referring to with dynamic memory in c?
the heap
what is the heap?
-memory that is allocated at runtime by code
-needs to be managed, freed up and returned after variables are no longer used
what is malloc() used for?
-gets a pointer to a portion of memory
-if it fails, returns null
how would you use malloc?
char str = (char) malloc(sizeof(char)*100);
strcpy(str, “hellooo”);
(char*) casts pointer to be type char *
how do you free up memory again after allocating heap memory?
free(pointer_name);
what is a struct?
a user-defined grouping of variables or even other structs.
what would a struct of a person with attributes name, age and gender look like?
struct person {
char name[20];
int age;
char gender;
};
for a structure, person, how would it be declared?
struct person Person1
how can attributes of a struct be accessed elsewhere in code with dot notation?
-using dot notation
e.g
person.age = 30;
strcpy(person.name, “Alan”);
how can attributes of a struct be accessed through a pointer?
struct person *p = &person1
//creates a pointer, p, to an instance of the struct pointer
p->age = 30
strcpy(p->name, “Alan”);
what does API stand for?
application programming interface
what is an example of an API?
-files declared in header that we call functions from
-e.g. <string.h> and functions like strcpy()</string.h>
with reference to reading from files, what is serial access?
-reading data from the beginning of the files sequentially through to the end.
-involves a file pointer that moves from the start to the end
what can the method getchar() be used for?
-returns the next input character each time it is called.
what does putchar() do?
-replaces a single character
what is needed before manipulating files?
-needs to be opened with fopen()
how would you open and then close a file?
FILE *fp;
//declare a file pointer
fp = fopen(“filename.txt,”r”);
//opens file to be read
fclose(fp)
what does the function fgets(char *line, int maxline, FILE *fp) do?
-allows us to work with lines of text
-max line length passed as a variable