gpt4 book ai didi

c - 为函数中的指针赋值时出现段错误

转载 作者:太空狗 更新时间:2023-10-29 17:22:12 25 4
gpt4 key购买 nike

长期倾听者,第一次来访者。

如果这个问题已经得到解决,我深表歉意(我想这已经被广泛讨论),但我已经搜索了很多关于指针和其他看似相关的主题的问题,但我仍然我无法解决我的问题。

我目前正在为类(class)项目编写一个 string 库,当我尝试这个时遇到段错误:

#include "str2107.h"
#include <stdio.h>

void lstrip(char *s) {

char *p, *q;
p = q = s;

while (*p == ' ' && *p != '\0') {
*p++;
}

while (*p != '\0') {
*q = *p; //this is where the actual segmentation fault occurs.
p++;
q++;
}

*q = '\0';
}

我的主程序是这样的:

#include <stdio.h>
#include <stdlib.h>
#include "str2107.h"


int main(int argc, char** argv) {

char *z1 = " weeee";
printf("lstrip function\n");
printf("%s\n",z1);
lstrip(z1);
printf("%s\n",z1);

return 0;
}

最佳答案

z1 指向一个字符串文字 并且修改一个字符串文字是undefined behavior .或者,您可以使用以下可修改的 z1 声明:

char z1[] = "      weeee"; 

如果我们看一下 C99 草案标准部分 6.4.5 String literals 段落 6 说(强调我的):

It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

WhozCraig 指出这一行的其他几点:

while (*p == ' ' && *p != '\0') {

可以更简洁地写成:

while (*p == ' ' ) {

你在这里也使用了间接:

*p++;

但您实际上并没有使用结果值,因此您可以将其更改为:

p++;

关于c - 为函数中的指针赋值时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19663186/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com