编程代考 Discussion week 2

Discussion week 2

¡ñ Unix Commands
¡ñ Command Line Arguments
¡ñ Pointers
¡ñ Structures
¡ñ Code Compilation Command

Unix Commands
add execution permission to a file main.c:
¡ð chmod +x main.c
list information about current directory: ls print the current directory: pwd
change the current directory: cd dirname make a new directory: mkdir
remove a file or directory: rm
¡ð Using with -r removes contents of directory recursively
¡ñ Kill a running process: kill print the number of lines, words and bytes in files : wc file1

Command Line Arguments
int main (int argc, char *argv[]){…}
¡ñ int argc : number of arguments + 1
¡ñ char** argv : array of character pointers listing all the arguments.
¡ñ argc is the length of argv
¡ñ argv[0] is the name of the program
¡ñ argv[1] is the first argument
¡ñ ./prog first second third

int main(int argc, char** argv) {
// Print the name of the program.
printf(¡°Program name is: %s¡±, argv[0]);
// Print all cmd line arguments.
for (int i=1; i < argc; ++i) printf(¡°Argument[%d] = %s¡±, i, argv[i]); The address of a variable can be obtained by preceding the name of the variable with an & sign ¡ð p = &myvar ¡ñ The value stored in the variable that is pointed to by a pointer p is accessed by using * operator ¡ð val = *p ¡ñ Pointers can be moved mathematically ¡ð p++ (increment by sizeof(int)) ¡ð p-- (decrement by sizeof(int)) ¡ñ Arrays can be treated like pointers ¡ð arr[i] and *(arr+i) are the same (access index i of arr) Structures struct point{ int main(){ struct point p; printf ("x = %d, y = %d\n", p.x, p.y); Structures - Accessing objects with pointers struct point{ int main(){ struct point* p=(struct point*)malloc(sizeof(struct printf ("x = %d, y = %d\n", p->x, p->y);

Code Compilation Command
¡ñ GCC (GNU Compiler Collection) is a toolchain to compile C programs among many other.
¡ñ Default usage to compile C programs using ¡®gcc¡¯ tool in GCC
¡ð gcc prog.c
¡ñ By using with -o option, we can give the executable output file a desired name instead of the default one (a.out)
¡ð gcc prog.c -o out
¡ð run using: ./out ¡ñ
-std=c99 : This command will use the c99 version of standards for
compiling the prog.c program
For more information, run following command from terminal

Lab Grading Policy
¡ñ Lab exercise: 70% credits for attending the lab and submitting the exercise on canvas
¡ð Make sure to sign in the attendance sheet before you leave the lab
¡ñ Take home Quiz: 30% credits (taken on canvas, deadline Tuesday

Today¡¯s Task
¡ñ Quiz – on canvas
¡ñ Lab Exercise:
¡ð The list.c file contains a linked list which looks like this:
2 -> 6 -> 10
¡ð Take one integer as command line argument and insert it into the list so that the list
remains sorted
¡ð Add your code in the insert_list() function