简体   繁体   English

为什么我的代码会导致细分错误?

[英]Why does my code cause a Segmentation fault?

When I run the following code, it shows "Segmentation fault (core dumped)". 当我运行以下代码时,它显示“分段错误(核心已转储)”。 Could you help me figure out the mistake I made? 你能帮我找出我犯的错误吗?

#include <stdio.h>

int str_len(char *s);

int main()
{

    int m;
    char a[] = "Hello, world";
    char *pa;
    *pa = a[0];
    m = str_len(pa);
    printf("The length of the string is %d.\n", m);
    return 0;

}

int str_len(char *s)
{

    int n;
    for (n = 0; *s != '\0'; s++)
            n++;
    return n;

}

Error in code : Assigning a character byte to a pointer. 代码错误 :将字符字节分配给指针。 Technically it's ok, but the pointer does not contain a valid address. 从技术上讲可以,但是指针不包含有效地址。 The error carries on and str_len receives that character thinking it is a byte. 错误继续进行,str_len认为它是一个字节而接收到该字符。 Trying to access that invalid address may cause the Segmentation Fault. 尝试访问该无效地址可能会导致分段错误。 pa char pointer is not initialized. pa char指针未初始化。 Hence, *pa = a[0] is like trying to say address_memory_for_pointers = a[0] . 因此, *pa = a[0]就像试图说address_memory_for_pointers = a[0] Try running: 尝试运行:

int m;
char a[] = "Hello, world";
char *pa = a;
m = str_len(pa);
printf("The length of the string is %d.\n", m);
return 0;

Using index with array name will always refer to address of particular element at that index. 使用带有数组名的索引将始终引用该索引处特定元素的地址。

*pa = a[0]; this will assign the pa to address of first element of array a , not the address of whole array. 这会将pa分配给数组a的第一个元素的地址,而不是整个数组的地址。 You should assign *pa = a; or *pa = &a; 您应该指定*pa = a; or *pa = &a; *pa = a; or *pa = &a; if you are intended to make pa to point the whole array. 如果要使pa指向整个数组。

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

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