Pointers and Strings
- Another way to access a contiguous memory track, rather than an array, is with a pointer.
- Since we are dealing with strings, which are composed of characters, we will use pointers to characters, or rather, char *s.
- However, pointers only hold one address, they cannot hold every character in a character array.This means that when we use a char * to keep track of a string, the character array containing the string must already exist (given either statically or dynamically).
Here’s how you can use a character pointer to trace a string.
char label[] = "Single"; char label2[10] = "Married"; char *labelPtr; labelPtr = label;
We would have something like the following in memory (e.g., assuming the array label has started to memory address 3000, etc.
Note: Since the pointer has been assigned the address of an array of characters, the pointer should be a character pointer — the types should match.
Likewise, to assign the address of an array to a pointer, we do not use the address-of (&) operator for the name of an array (like labels) behaves like the root address of that array in this setting.This is also why you do not use ampersand when passing a string variable through scanf().
Example:
int id;
char name[30];
scanf("%d%s", &id, name);
Now we can use labelPtr as an array name label. Thus, we might access the third character of the string with:
printf("Third char is: %c\n", labelPtr[2]);
It is important to remember that the only reason why the labelPtr pointer allows us to access the label array is because we have put labelPtr on it.Consider that we are doing the following:
labelPtr = label2;
Now the labelPtr pointer does not refer to the label, but now to label 2 as follows:
labelPtr = label2;
So, now when we index with labelPtr, we reference characters in label2.
printf("Third char is: %c\n", labelPtr[2]);
printer, the third character of the label2 array.
Example Program:
#include<stdio.h>
main()
{
char name[]="gitam university";
char *pname=name;
int i;
//1st method of printing string using pointers
printf("Name is %s \n",pname);
//2nd method of printing string using pointers with loop
printf("\n Name is : ");
for(i=0;name[i]!="\0";i++)
{
printf("%c",*pname);
pname++;
}
}
Output:
