我有一個字符串:「這是一個簡單的字符串」printf(「%s」,pch)VS.而(輸出( 「%C」 PCH [I]))?
我的目標是找到(與strstr
)「簡單」,並將其替換爲「樣本」。
CODE:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main (int argc, char *argv[]){
char *str;
char *pch;
int i=0;
if((str=malloc(BUFSIZ))==NULL){
printf("\n\t MEMORY ERROR");
exit(1);
}
if((pch=malloc(BUFSIZ))==NULL){
printf("\n\t MEMORY ERROR");
exit(1);
}
str="This is a simple string ";
pch=str;
while(str[i]!='\0'){
printf("%c",str[i]);
i++;
}
printf(" -1break\n");
while((*pch!='\0')){
printf("%c",*pch);
pch++;
}
printf(" -2break\n");
printf("%s %d %d %d %d\n",str,strlen(str),sizeof(*str),BUFSIZ,(BUFSIZ-strlen(str)));/*OK*/
if((pch=strstr(str,"simple"))!=NULL){
printf("%s \n",pch); **/*OK*/**
while((*pch!='\0')){
printf("%c",*pch);
pch++;
} **/*SEG FAULT*/**
strncpy(pch,"sample",6);
printf("OK\n");
}
printf("%s %d\n",str,strlen(str));
printf("\n");
return 0;
}
OUTPUT:
$ ./strstr
This is a simple string -1break
This is a simple string -2break
This is a simple string 24 1 8192 8168
simple string
Segmentation fault
$
問題:
不能取代 「簡單」 與 「樣本」。
問題:
如果pch
點到正確的「的「簡單」爲什麼不能strncpy
更換6個「樣品」的信嗎?
'BUFSIZ'的價值是什麼?你也可以通過'malloc'將內存分配給'str'和'pch',然後很快重新調整,所以你在這裏泄漏內存。 – 2013-04-29 13:36:55
-1。還有另一個類型的問題:'char * var =「hello world」; strcpy(var,「hello universe」);'或'char * var =「hello world」; var [5] = a;' – anishsane 2013-04-29 13:56:05
anishane多數民衆贊成什麼即時通訊試圖瞭解 strcpy和var [5] = a ??之間有什麼區別? – 2013-04-29 14:05:32