-1

文字列があります:「これは単純な文字列です」

私の目的は、strstr「シンプル」を見つけて「サンプル」に置き換えることです。

コード:

#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;
}

出力:

$ ./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"simple" の 's' を正しく指している場合、なぜ" strncpysample" の 6 文字を置き換えることができないのですか?

4

2 に答える 2

3

要約すると、ポインタは/ /または静的 char 配列strで割り当てられたメモリのような読み取り/書き込みメモリ領域を指す必要がありますまたはmalloccallocreallocchar str[50]char str[] = "simple string";

char *str = "simple string"strここではリテラル文字列を指しています。また、リテラル文字列は読み取り専用のメモリ領域に保存されるため、編集することはできません

コード評論家:

1)最初に次の行が間違っています

str="This is a simple string ";

str にメモリを割り当てましたが、それを使用していません。ポインターを変更しました。ポインターは、元のメモリ領域 (malloc で割り当てられた) ではなく、リテラル文字列 (定数文字列) を指しています。そのはず:

strcpy(str,"This is a simple string ");

についても同じ

pch = str;

pchの同じリテラル文字列を指していますstr

pch=strstr(str,"simple")

pchstrはリテラル文字列であるため、ここでもリテラル文字列を指しています

2) 次の行が間違っています

strncpy(pch,"sample",6);

pchリテラル文字列を指していて、リテラル文字列を指すポインターにコピーすることは未定義の動作であり、これによりクラッシュが発生します

コード修正:

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);
    }

    strcpy (str, "This is a simple string ");
    if((pch=strstr(str,"simple"))!=NULL) {
        strncpy(pch,"sample",6);
    }
    printf("%s\n", str);
}
于 2013-04-29T13:39:11.300 に答える