Professional Documents
Culture Documents
• Strings
• Characters and Strings
• Pointers and Strings
Pointer Declaration
int *j;
• The ‘*’ in declaration tells the compiler that the variable is a pointer
• Operator *: value at address
• int *j : value at the address contained in j is an int.
• The int says that the pointer variable can point to an integer variable
Pointer
j = &i;
• j is a variable that contains the address of another variable i.
• Being a variable j also gets memory allocated to it.
i j
*j
5 62334
62334 62366
• Special name for j is pointer variable.
• Can hold address of other variable but one at a time.
Operator Precedence and Associativity
Null Pointer
• A pointer may be initialized to NULL, 0 or an address.
int *p = NULL;
• A pointer with the value NULL points to nothing.
• Initializing a pointer to 0 is equivalent to initializing a pointer to
NULL, but NULL is preferred.
• The value 0 is the only integer value that can be assigned directly
to a pointer variable.
• Constant NULL defined in <stdio.h>
• No comparison of Null pointer to general pointer.
Example: NULL Pointer
Example: NULL Pointer
Void Pointer
void *p;
5
\0
char *s = “Namaste!”
Constant string
• Solution:
char *s1, *s2= “Namaste!”;
s1 = s2;
Character Pointer: Useful when?
• We cannot change the value once a string is being assigned a value
char s1[]= “Namaste!”
s1[]= Hello!; Invalid!
• Why???
Character Pointer: Useful when?
• We cannot change the value once a string is being assigned a value
char s1[]= “Namaste!”
s1[]= Hello!; Invalid!
• Solution:
char *s1= “Namaste!”;
s1 = “Hello!”;
Example
Example
Example
Example
Example
Constant String
Example: Character Pointer and Strings
Constant Pointer
Constant String
• strlen()
• strcpy()
• strcat()
• strcmp()
String Function: strlen()
Example: strlen()
Example: strlen()
Example: User Program to Compute strlen
Example: User Program to Compute strlen
String Function: strcpy()
• We cannot assign a string to another
char s1[]= “Namaste!”
char s2[10];
s2 = s1; Invalid!
• Solution:
char *s1, *s2= “Namaste!”;
s1 = s2;
String Function: strcpy()