gpt4 book ai didi

c++ - char s1[ ] = "xyz"和 char *s1 = "xyz"

转载 作者:太空宇宙 更新时间:2023-11-04 07:25:56 25 4
gpt4 key购买 nike

<分区>

我正在尝试用值初始化 s1,然后在 squeeze() 中初始化。我正在改变 s1。指针初始化会引发段错误,但数组版本工作正常。有人可以告诉我我是否可以使用指针版本来做到这一点,这有什么问题?可能是因为我没用过malloc ??

int main() {

char s1[] = "xyz abc zzz" ; // this works fine.
// char *s1 = "xyz abc zzz"; // if i initialize like this it throws a seg fault.

char *s2 = "abx xxx xxx" ;
squeeze(s1,s2) ;
puts (s1) ;
return 0 ;

}

void squeeze(char *s1, char *s2 ) {

int i , j, k = 0;

for (i=0 ; s1[i] != '\0' ; ++i) {

for (j=0; s2[j] != '\0'; j++) {
if (s2[j] == s1[i])
break;


}
if(s2[j] == '\0')

s1[k++] = s1[i] ;

}

s1[k++] = '\0' ;

}

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