我是一個C語言的初學者,通過書本學習C語言,下面是我對6.18-2寫一個從源字串中洗掉substr的方法的解決方案,它不作業。
#include <stdio.h>
char *find_char(char const *source。char const *chars)。
{
int offset = 0;
if (source == NULL || chars == NULL) literal">NULL || *source == ''/span> || *chars == ''/span>)
return NULL。
while (*chars != ''/span>)
{
while (*(source offset) != '')
if (*(source offset ) == *chars)
return source --offset;
chars ;
offset = 0;
}
return NULL。
}
int del_substr(char *str, char const *substr).
{
int offset = 0;
int suboffset = 0;
if (str == NULL || substr == NULL)
return 0;
while(*(str offset) != ''/span>)
{
while( *(str offset) != '' && *(str offset ) == *(substr suboffset ) )。
if(*(substr suboffset) == '')
{
while ((*(str offset - suboffset) = *(str offset )) != ' ')
;
return 1。
}
offset 。
suboffset = 0;
}
return 0;
}
int main()
{
char *source = "hello, people." ;
char *chars = "peo";
del_substr(source, chars);
printf("result:%s
", source)。)
return 0;
}
uj5u.com熱心網友回復:
你不可以改變一個字串字面。任何試圖改變字串字面的行為都會導致未定義行為。
所以在main中你需要使用宣告
char source[] = "hello, people." ;
代替
char *source = "hello, people." ;
這樣的陳述句
while( *(str offset) != ' && *(str offset )== *(substr suboffset ))。
在這里讀取變數offset并同時使用后綴增量運算子呼叫未定義行為。
這個遞增
offset ;
跳過許多字符。你需要寫
offset = offset - suboffset 1。
uj5u.com熱心網友回復:
source和chars都是指向字串字面的指標,你不能修改一個字串字面,根據語言規則,這樣做的程式的行為是未定義的。source必須被宣告為一個char陣列:
char source[] = "hello, people." ;
這樣,字串的拷貝被存盤在陣列中,因此,它是可修改的。
我猜想,你的書中一定談到了字串字面意義以及你應該如何處理它們。如果不是這樣的話,我們就不能真正稱其為書。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/315467.html
標籤:
下一篇:我在C語言中實作了doublequeue(Deque)。當我呼叫deque_from_back()時,程式立即退出。

