简体   繁体   English

在C语言的字符串中打印字符时出现分段错误

[英]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. 我简化了分配工作的那部分,从而以更简单的代码给了我Seg Fault。

#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'. 然后是“细分错误: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. 我不明白为什么这是个问题,因为我只是在打印。

This is a precedence issue. 这是一个优先问题。 *sptr[i] parses as *(sptr[i]) , but you need (*sptr)[i] . *sptr[i]解析为*(sptr[i]) ,但您需要(*sptr)[i]

It crashes because sptr[i] means *(sptr + i) , ie at i = 0 you're simply dereferencing sptr (giving you sentence ), then dereferencing that, giving you *sentence (ie the first character of sentence ). 它崩溃,因为sptr[i]是指*(sptr + i)即在i = 0 ,你只是简单地提领sptr (给你sentence ),然后提领的是,给你*sentence (即第一个字符sentence )。 But at i = 1 you're doing sptr[1] (ie *(sptr + 1) ), which tries to access memory next to the sentence variable, then treats it as another pointer to dereference. 但是在i = 1您正在执行sptr[1] (即*(sptr + 1) ),该尝试尝试访问sentence变量旁边的内存,然后将其视为另一个取消引用的指针。 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. 即使您很幸运,并且内存中的sentence旁边恰好有一个有效的指针,连续的迭代也将尝试取消引用越来越多的垃圾值作为指针。

Of course, you could avoid the whole problem by having printword take a char * and simply passing sentence to it. 当然,您可以通过让printword取一个char *并简单地将sentence传递给它来避免整个问题。

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] . 典型的新C程序员会犯错误,认为*str[i]str[][i]相同,不是* 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: 因此*str[i]就像:

**(arr + i)

what you want is: 您想要的是:

*(*(arr) + i)

which is like: 就像:

*(arr[i])

I hope this helps!!!! 我希望这有帮助!!!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM