Thread: How to change a letter in a char pointer?

  1. #1
    Registered User marcelo.br's Avatar
    Join Date
    Nov 2018
    Posts
    45

    Question How to change a letter in a char pointer?

    This pointer comes from a function like this, and I want to remove a part of the string
    Code:
    void search(char *DirectoryPath)
    Code:
    #include <stdio.h>
    int main() {
       // How do I make it work?
       char *A = "Slackware";
       A[5] = '\0';
       puts(A); // Slack
    
       // It works! char A[] = "Slackware";
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Well there are pointers to memory you can't change, such as
    char *A = "Slackware";

    Which should be declared as const to begin with.
    Code:
    $ cat foo.c
    #include <stdio.h>
    #include <stdlib.h>
    int main()
    {
        char *A = "Slackware";
        puts(A);
        return 0;
    }
    $ gcc -Wall -Wextra -Wwrite-strings foo.c
    foo.c: In function ‘main’:
    foo.c:5:15: warning: initialization discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]
        5 |     char *A = "Slackware";
          |               ^~~~~~~~~~~

    Then there are pointers to memory you can change.
    Code:
    $ cat foo.c
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    int main()
    {
        char *A = malloc(20);
        strcpy(A,"Slackware");
        A[5] = '\0';
        puts(A);
        free(A);
        return 0;
    }
    $ gcc -Wall -Wextra -Wwrite-strings foo.c
    $ ./a.out 
    Slack
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Change one element of string pointed by char pointer
    By Ducky in forum C++ Programming
    Replies: 16
    Last Post: 02-15-2013, 09:29 PM
  2. Replies: 12
    Last Post: 11-24-2012, 04:10 AM
  3. Change one letter from a string
    By gunitinug in forum C Programming
    Replies: 4
    Last Post: 12-01-2011, 04:05 AM
  4. last letter of char pointer
    By p595285902 in forum C Programming
    Replies: 14
    Last Post: 04-12-2011, 10:54 AM
  5. Problem with a char variable set as a letter
    By 7smurfs in forum C++ Programming
    Replies: 6
    Last Post: 12-10-2004, 01:25 PM

Tags for this Thread