Professional Documents
Culture Documents
(Programming in C) : (Pointers and Strings)
(Programming in C) : (Pointers and Strings)
APRIL 3, 2019
MODULE 3
ELECTRONICS S4
What are Pointers?
A pointer is a variable whose value is the address of another variable, i.e., direct address of the
memory location. Like any variable or constant, you must declare a pointer before using it to
store any variable address. The general form of a pointer variable declaration is −.
datatype *pointer_name;
Data type of a pointer must be same as the data type of the variable to which the pointer variable
is pointing. void type pointer works with all data types, but is not often used.
#include<stdio.h>
void
main()
{
int a = 10;
int *ptr; //pointer declaration
ptr = &a; //pointer initialization }
Pointer variablea always point to variables of same datatype. Let's have an example to showcase
this:
#include<stdio.h>
void main()
{ float a;
int *ptr;
ptr = &a; // ERROR, type mismatch }
If you are not sure about which variable's address to assign to a pointer variable while
declaration, it is recommended to assign a NULL value to your pointer variable. A pointer which
is assigned a NULL value is called a NULL pointer.
#include <stdio.h>
In ordinary assignment involving pointers, the pointer is an alias for its target. In pointer assignment, the pointer is
associated with a target. If the target is undefined or disassociated, the pointer acquires the same status as the
target. The pointer assignment statement has the following form:
pointer-object
Is a variable name or structure component declared with the POINTER attribute.
target
Is a variable or expression. Its type and kind parameters, and rank must be the same as pointer-object. It
cannot be an array section with a vector subscript.
If you don't know what arrays are, we recommend you to check C arrays.
char s[5];
The scanf() function reads the sequence of characters until it encounters a whitespace
(space, newline, tab etc.).
Output
int main()
{
char str[50]; printf("Enter string: "); gets(str);
displayString(str); // Passing string to a function.
return 0;
}
void displayString(char str[])
{
printf("String Output: ");
puts(str); }
int main(void) {
char name[] = "Harry Potter";
printf("%c", *name); // Output: H
printf("%c", *(name+1)); // Output: a
printf("%c", *(name+7)); // Output: o
char *namePtr;
namePtr = name;
printf("%c", *namePtr); // Output: H
printf("%c", *(namePtr+1)); // Output: a
printf("%c", *(namePtr+7)); // Output: o }
C – String functions
END