c for Java Programmers
c for Java Programmers
Advanced Programming
Credits
Software Construction (J. Shepherd)
Operating Systems at Cornell (Indranil
Gupta)
void main(void){
start=end=NULL;
add(start, end, 2); add(start, end, 3);
printf(“First element: %d”, delete(start, end));
}
#include <stdio.h>
void main(void)
{
printf(“Hello World. \n \t and you ! \n ”);
/* print out a message */
return;
}
$Hello World.
and you !
$
Feb 7, 2025 Advanced Programming 20
Spring 2002
Dissecting the example
#include <stdio.h>
include header file stdio.h
# lines processed by pre-processor
No semicolon at end
Lower-case letters only – C is case-sensitive
void main(void){ … } is the only code executed
printf(“ /* message you want printed */ ”);
\n = newline, \t = tab
\ in front of other special characters within
printf.
printf(“Have you heard of \”The Rock\” ? \n”);
Feb 7, 2025 Advanced Programming 21
Spring 2002
Executing the C program
int main(int argc, char argv[])
argc is the argument count
argv is the argument vector
array of strings with command-line
arguments
the int value is the return value
convention: 0 means success, > 0 some
error
can also declare as void (no return value)
argc argv
data
args
-l library
-E preprocessor output only
becomes
if ((i) < 100) {…}
void main(void)
{
int nstudents = 0; /* Initialization, required */
return ;
}
#include <stdio.h>
void main(void)
{
int i,j = 12; /* i not initialized, only j */
float f1,f2 = 1.2;
s = x;
printf(“%d %d\n”, x, s);
100000 -31072
smallNumber x;
byte b;
String name;
is like
#define Red 0
#define Orange 1
#define Yellow 2
typedef enum {False, True} boolean;
Code
400
all malloc()s Data - Heap Dynamic memory
560
&x 42
int * int
Feb 7, 2025 Advanced Programming 62
Spring 2002
Data objects and pointers
If p contains the address of a data
object, then *p allows you to use that
object
*p is treated just like normal data object
int a, b, *c, *d;
*d = 17; /* BAD idea */
a = 2; b = 3; c = &a; d = &b;
if (*c == *d) puts(“Same value”);
*c = 3;
if (*c == *d) puts(“Now same value”);
c = d;
if (c == d) puts (“Now same address”);
Feb 7, 2025 Advanced Programming 63
Spring 2002
void pointers
Generic pointer
Unlike other pointers, can be assigned
to any other pointer type:
void *v;
char *s = v;
Acts like char * otherwise:
v++, sizeof(*v) = 1;
2-dimensional array
int weekends[52][2];
weekends
void main(void) {
char user1line[20]; /* different from earlier
user1line[30] */
. . . /* restricted to this func */
}
void dummy(){
extern char user1line[]; /* the global user1line[30] */
. . .
}
hw.c mypgm.c
fp=f;
gp=g;
int i = fp();
double *g = (*gp)(17); /* alternative */
void main(void) {
myproc(10); /* call myproc with parameter 10*/
mycaller(myproc, 10); /* and do the same again ! */
}