How to replace char with char *

general newbie here. I tried to replace the character in char *, but my program gives an error

#include <stdio.h>

int main(int argc, char **argv)
{
    char *mystring ="love is alweys better yoe";
    int count = 1;

    for (count ;  count < 23; count++)
    {     
    if ((mystring[count] == 0x65 )) //&& ((mystring[count+1] > 0x41) && (mystring[count+1] < 0x7A))) 
    {
      mystring[count] = 0x45; //here occur the freezing
      printf ("%c\n", mystring[count]); 
      //break;
    };
    };

    printf("%s\n",mystring);
    return 0;
}
+3
source share
3 answers

char *mystring ="love is alweys better yoe"

makes mystring read-only

you need to copy the string to the buffer before you can change it.

eg.

char mystring[128];
strcpy( mystring , "love is alweys better yoe" );
+10
source

Stack placement

char *mystring ="love is alweys better yoe";

This creates a string literal in read-only memory, and you cannot subsequently write it to change characters.

Instead, you should initialize your line as follows:

char mystring[] ="love is alweys better yoe";

An array of characters of size 26 bytes will be allocated here - 1 byte per character terminated by a null character \0.

, (.. \0), , , .

( , ). , , :

int bufferSize = 26;
char* mystring = malloc(bufferSize);
strncpy(mystring, "love is alweys better yoe", bufferSize);

free , :

free(mystring);

free ing , char* , , free. free , .

, realloc:

char* mybiggerString = realloc(mystring, bufferSize + 10);
strncpy(mystring, "I can fit more in this string now!", bufferSize);
+9

" char *" . , "", " " - . . "", "".

char *mystring ="love is alweys better yoe";, mystring . , . . ( .exe, .exe , .exe. , - , .)

Decision. Use the modifiable portion of memory. Write it like this: char mystring[] = "love is alweys better yoe";. The string literal will still exist in your program, but this tells the program to create a buffer (in memory, which can be modified) and copy the literal to the buffer. This buffer is exactly the same length as the literal one, so you still cannot add to the string - just change the existing characters or disable it (by writing a zero byte somewhere in the middle).

+5
source

Source: https://habr.com/ru/post/1778026/


All Articles