Teja
Teja

Reputation: 13534

Dereferencing string pointers in C

I am new to C and I would like to know the difference between the below two snippet codes.When I try executing first one it works fine,but when I run the second one it gives me segmentation fault.Whats the reason for this behavior?

        printf("%c\n",*strptr++);

        printf("%c\n",*(strptr+i));

Here is the below code.

#include<stdio.h>

int main(void)
{
        char str[100]="My name is Vutukuri";
        int i=0;
        char *strptr;

        strptr=str;

        while(*strptr != '\0')
        {
                printf("%c\n",*strptr++);
                //printf("%c\n",*(strptr+i));
                //i++;
        }
        return 0;
}

Upvotes: 0

Views: 5150

Answers (3)

Imp
Imp

Reputation: 8609

Apparently, the address strptr refers to an allocated place in memory, while strptr + i points to an unallocated place. If you allocate a string as

char s[LENGTH];

or

char* s = (char*)malloc(LENGTH * sizeof(char));

then you can only use the characters from s[0] to s[LENGTH - 1] (and the string itself can only be LENGTH - 1 long, so there is place for a null terminator). In your case, the pointer strptr + i is probably not in the range s...s + LENGTH - 1.

Upvotes: 2

gabitzish
gabitzish

Reputation: 9691

Maybe you want to replace i with 1.

  • ++ operator first uses the initial value, and then it increments it.
  • +operator calculates the new value and then uses it.

Upvotes: 1

orlp
orlp

Reputation: 117681

Entirely different.

The first snippet prints the character at strptr and then increments strptr by one.

The second snippet prints the character at strptr + i.

Upvotes: 3

Related Questions