user700048
user700048

Reputation: 119

c pointer with string

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

Upvotes: 1

Views: 18530

Answers (3)

ankyAS
ankyAS

Reputation: 301

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);
}

Upvotes: 0

Philip
Philip

Reputation: 5917

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.

Upvotes: 2

Erik
Erik

Reputation: 91260

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.

Upvotes: 4

Related Questions