CSCI 4061
Discussion week 2
Overview
● Unix Commands
● Command Line Arguments
● Pointers
● Structures
● Code Compilation Command
Unix Commands
● To add execution permission to a file main.c:
○ chmod +x main.c
● To list information about current directory: ls
● To print the current directory: pwd
● To change the current directory: cd dirname
● To make a new directory: mkdir
● To remove a file or directory: rm
○ Using with -r removes contents of directory recursively Command Line Arguments int main (int argc, char *argv[]){…} ● int argc : number of arguments + 1 Example 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]);
}
Pointers
● 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 (1/2)
struct point{
int x,y;
};
int main(){
struct point p;
p.x=10;
p.y=20;
printf ("x = %d, y = %d\n", p.x, p.y);
}
Structures - Accessing objects with pointers (2/2)
struct point{
int x,y;
};
int main(){
struct point* p=(struct point*)malloc(sizeof(struct
point))
p->x=10; Code Compilation Command ● GCC (GNU Compiler Collection) is a toolchain to compile C programs ● Default usage to compile C programs using ‘gcc’ tool in GCC ● By using with -o option, we can give the executable output file a desired ● -std=c99 : This command will use the c99 version of standards for ● For more information, run following command from terminal Lab Grading Policy ● Lab exercise: 70% credits for attending the lab and submitting the ● Take home Quiz: 30% credits (taken on canvas, deadline Tuesday Today’s Task ● Quiz – on canvas ● Lab Exercise: 2 -> 6 -> 10 remains sorted
● To print the number of lines, words and bytes in files : wc file1
● Kill a running process: kill
● 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
p->y=20;
printf (“x = %d, y = %d\n”, p->x, p->y);
}
among many other.
○ gcc prog.c
name instead of the default one (a.out)
○ gcc prog.c -o out
○ run using: ./out
compiling the prog.c program
○ $ man gcc
exercise on canvas
○ Make sure to sign in the attendance sheet before you leave the lab
midnight)
○ The list.c file contains a linked list which looks like this:
○ Take one integer as command line argument and insert it into the list so that the list
○ Add your code in the insert_list() function