[ON-GOING] C Review
2024-07-18
Variables and Operators
The main data types in C: int
, float
, double
, and char
.
printf
symbol | type |
---|---|
%d or %i | int |
%f | double or float |
%c | char |
float
is 4 bytes
double
is 8 bytes
Constants
Never change.
const int DAYSINWEEK = 7;
Casting Types
There are two types of conversions, implicit and explicit. When you set one variable to be the same as another, such as a = b above, but their types do not match, the compiler will try to convert them. However, this can be dangerous as you might not know what values will be in the variable at runtime, and it might not be implicitly convertible to another type. Our example above was implicit, the compiler in this case will make a best guess.
double testScore;
int displayScore;
displayScore = (int)testScore;
Operators
Nothing noteworthy.
Pointers
Pointer Arithmetic
The only arithmetic operations allowed for pointers are addition and subtraction. Conceptually, adding to (or subtracting from) a pointer means the pointer will point to some new address. Multiplication is not allowed because the address of a byte of memory is usually a large number; therefore, multiplying an address may yield an even larger number, possibly representing an address outside the bounds of the available memory space. Division is not allowed as it potentially allows a pointer to illogically point to an address with a non-integer index.
The important thing to note here is that adding n to a pointer does not increment the address to point to a value n bytes away. It moves the pointer by n * (size of the data type in bytes). For example, if a pointer to an int, the size of which is four bytes, initially contains address 100 (we will use a decimal address for simplicity), and three is added to the pointer, the pointer will now point to address 112.
#include <stdio.h>
int main() {
double* ptr1;
ptr1 += 5;
ptr1 -= 4;
}
Pointers & Arrays
Struggle bus for this one…. Not great. Dereferences were kind of weird, and single quotes got me stuck for a while for some reason.
#include <stdio.h>
#include <string.h>
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
char s[] = "Farmer Jack realized that big yellow quilts were expensive!!";
int *ptr = &arr[9];
for (int i = 9; i >= 0; i--){
printf("%i",arr[i]);
}
char *ptr2 = &s[0];
for (int i = 0; i < strlen(s); i++) {
*ptr2 = '#';
ptr2++;
}
}
Memory Management
Function | Use Case |
---|---|
malloc() | Use this function to reserve as many bytes as you want on the heap |
calloc() | Use this function to reserve memory for some number of ints, doubles, or any other data type. |
realloc() | Use this function to expand or contract a block of reserved memory (reserved by either malloc() or calloc()). |
free() | Use this function to release previously allocated memory. |
Small Projects
String Copier aka poor-man strcpy()
#include<stdio.h>
#include<string.h>
void copy(char* dst, char* src){
int ptr = 0;
while(*src != '\0'){
dst[ptr] = *src;
ptr++;
src++;
printf("%s", src);
}
printf("%s", dst);
}
int main(){
char srcString[] = "We promptly judged antique ivory buckles for the next prize!";
char dst[strlen(srcString+1)];
copy(dst, srcString);
}
Echo Server
[ … ]
LeetCode Practice
Palindrome Number (Easy)
Given an integer x
, return true
if x
is a palindrome (An integer is a palindrome when it reads the same forward and backward.), and false
otherwise.
Nothing too special here, just iterate over the x
value using % 10
. Placed the numbers into a char str
array in reverse order, then use atoi()
to change the type from char str
to int
. Finally, just compared and return. I didn’t find this overly complicated but my code definitely lacks in simplicity.
bool isPalindrome(int x) {
if (x < 0) {
return false;
}
char str[12];
int i = 0;
int num = x;
while (num > 0) {
str[i++] = num % 10 + '0';
num /= 10;
}
int reverse = atoi(str);
if (reverse != x) {
return false;
}
return true;
}
Merge Two Sorted Lists (Easy)
You are given the heads of two sorted linked lists list1
and list2
. Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2) {
// init our struct to return to user.
struct ListNode *dummy = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode *answer = dummy;
// we now know that both lists have elements.
while (list1 != NULL && list2 != NULL) {
// Compare elements until one of them goes NULL.
if (list1->val < list2->val) {
answer->next = list1;
list1 = list1->next;
} else {
answer->next = list2;
list2 = list2->next;
}
answer = answer -> next;
}
// Append the remainders.
// Condition ? value_if_true : value if false;
answer -> next = (list1 != NULL) ? list1 : list2;
/*
if (list1 == NULL) {
answer->next = list2;
} else {
answer->next = list1;a
}
*/
struct ListNode *head = dummy->next;
return head;
}
Remove Element (Easy)
Given an integer array nums
and an integer val
, remove all occurrences of val
in nums
in-place. The order of the elements may be changed. Then return the number of elements in nums
which are not equal to val
.
Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:
- Change the array
nums
such that the firstk
elements ofnums
contain the elements which are not equal toval
. The remaining elements ofnums
are not important as well as the size ofnums
. - Return
k
.
int removeElement(int* nums, int numsSize, int val) {
int write = 0;
for (int readIndex = 0; readIndex < numsSize; readIndex++) {
if (val != nums[readIndex]){
nums[write] = nums[readIndex];
write++;
}
}
return write;
}
Score of a String (Easy)
You are given a string s
. The score of a string is defined as the sum of the absolute difference between the ASCII values of adjacent characters.
Return the score of s
.
int scoreOfString(char* s) {
int size = 0;
for (int i = 0; i < strlen(s)-1; i++){
size += abs( (int)s[i] - (int)s[i+1] );
}
return size;
}
Convert the Temperature (Easy)
You are given a non-negative floating point number rounded to two decimal places celsius, that denotes the temperature in Celsius.
You should convert Celsius into Kelvin and Fahrenheit and return it as an array ans = [kelvin, fahrenheit]
.
Return the array ans
. Answers within 10-5 of the actual answer will be accepted.
Note that:
- Kelvin = Celsius + 273.15
- Fahrenheit = Celsius * 1.80 + 32.00
double* convertTemperature(double celsius, int* returnSize) {
*returnSize = 2;
double* arr = (double*)malloc(2 * sizeof(double));
arr[0] = (double)(celsius + 273.15);
arr[1] = (double)(celsius * 1.80 + 32.00);
return arr;
}
Find the Index of the First Occurrence in a String (Easy)
Given two strings needle and haystack
, return the index of the first occurrence of needle
in haystack
, or -1
if needle is not part of haystack.
int strStr(char* haystack, char* needle) {
for (int i = 0; i < strlen(haystack); i++) {
int match = i;
int tmp = i;
for (int j = 0; j < strlen(needle); j++) {
if (haystack[tmp] == needle[j]) {
if (j == strlen(needle)-1) {
return match;
}
tmp++;
} else {
break;
}
}
}
return -1;
}