1

Trying to learn pointers better I wrote this code. The intention was to print one character of a string at a time in a for loop. Again trying to learn how to increment a pointer and then dereference the pointer.

char *string = "abcdef";
char *pointer = &string; 

for (int i =0; i < 4; i++)

{   
    printf("the next charater is %c\n", *pointer);
    pointer = (char *)pointer + sizeof(char);
}

want it to print:

the next charater is a

the next charater is b

the next charater is c

the next charater is d

3 Answers 3

4
char *pointer = &string; 

should be

char *pointer = string; 

string is a pointer variable that contains the address of your string literal. You want the address of the string literal, so you should simply copy the value in string - not take the address of the local pointer variable - your current code gives you a pointer to a pointer to a string.

Additionally, pointer = (char *)pointer + sizeof(char); doesn't require a cast, and it should not use sizeof(char). When incrementing a variable of type pointer to X, incrementing it by one will increment it by sizeof(X) bytes - increment by one to point at the next X. Use pointer += 1; or ++pointer instead.

3
  • cool so this works, could you please explain why. I thought "&" was the address of operator. so why doesn't the *pointer contain the address of string in my sample code. What is *pointer referencing in my sample code
    – user700048
    Commented Apr 9, 2011 at 23:32
  • @user700048: string points at "abcdef" - it already contains an address. What you do gives you the address of a variable which contains the address of "abcdef" - a pointer to a pointer to "abcdef"
    – Erik
    Commented Apr 9, 2011 at 23:34
  • @user700048: You're confused because you didn't just write char *pointer = "abcdef" in the first place: it's already an address. :) Commented Apr 10, 2011 at 0:29
2

If you want to print (or otherwise process) the whole string one char at a time, you may use the following idiom:

char *p = /* ... */;

while (p && *p) {
    printf("next char: %c\n", *p++);
}

The condition first tests whether p is NULL, i.e. if it is wise to dereference p at all. If p is not NULL, *p tests whether you already reached the end of the string, denoted by the '\0' character, which happens to be 0.

0

If you want to use pointer to pointer to string then you can use like this:

char *string = "abcdef";
char **pointer = &string;
int i;
for (i =0; i < 4; i++)

{
    printf("the next charater is %c\n", **pointer);
    *pointer = *pointer + sizeof(char);
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.