User9123
User9123

Reputation: 774

Segmentation Fault when Printing Characters in String in C

I was working on an assignment and noticed I was getting a Seg Fault when I tried printing the individual characters of a string. This is strange because there is no segmentation fault when I remove the print statement.

I simplified that part of the assignment that gave me the Seg Fault in a simpler code.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


void printword( char **sptr){

    int i;

    for( i = 0; i < 6; ++i){

        printf( "%c\n", *sptr[i]);
    }
}

int main(){

    char *sentence = "This is my sentence\n";

    printf("Sentence is: %s", sentence);
    printword( &sentence );

}

When I run this code, Only the first letter prints, then right after a '?' followed by 'Segmentation fault: 11'. It seems that I can print any character from the string, however, just 1 character is my limit before a seg fault. I don't understand why this is an issue because I am simply printing.

Upvotes: 1

Views: 1932

Answers (2)

user5550963
user5550963

Reputation:

Typical new C programmers mistake, thinking that *str[i] is the same as str[][i] it is not it is more like str[i][0].

So, why is this happening? When you look at precedence [] is at the top. Take a look at this

The other way to look at it is:

arr[i][j]

is the like:

*(*(arr+i) + j)

thus *str[i] is like:

**(arr + i)

what you want is:

*(*(arr) + i)

which is like:

*(arr[i])

I hope this helps!!!!

Upvotes: 1

melpomene
melpomene

Reputation: 85887

This is a precedence issue. *sptr[i] parses as *(sptr[i]), but you need (*sptr)[i].

It crashes because sptr[i] means *(sptr + i), i.e. at i = 0 you're simply dereferencing sptr (giving you sentence), then dereferencing that, giving you *sentence (i.e. the first character of sentence). But at i = 1 you're doing sptr[1] (i.e. *(sptr + 1)), which tries to access memory next to the sentence variable, then treats it as another pointer to dereference. Even if you're lucky and there happens to be a valid pointer next to sentence in memory, successive iterations will just attempt to dereference more and more garbage values as pointers.

Of course, you could avoid the whole problem by having printword take a char * and simply passing sentence to it.

Upvotes: 2

Related Questions