0

In C language I am trying to assign a value to pointer string. I cannot use char array, I have to use pointer string. So please tell how can I do that?

I am doing something like this (code given), but when I run my code an error is prompted program stopped working.

#include <stdio.h>


int main (void) {

    char *myString = " ";
    int value = 1;

    myString[0] = value+'0';

    printf("%s\n",myString);

    return 0;
}
Raees Khan
  • 371
  • 1
  • 5
  • 20

1 Answers1

3

You cannot modify a string literal: myString is initialized to point to constant storage for the string literal. Attempting to modify it invokes undefined behavior. Use strdup() to create a copy of the string:

#include <stdio.h>
#include <string.h>

int main(void) {
    char *myString = strdup(" ");
    int value = 1;

    myString[0] = value + '0';

    printf("%s\n", myString);

    free(myString);

    return 0;
}

strdup() is a function standardized in POSIX, that allocates a block of memory from the heap long enough to receive a copy of its string argument. It copies the string into it and returns a pointer to the block. Such a block can be modified, and should be freed with free() when no longer needed.

chqrlie
  • 131,814
  • 10
  • 121
  • 189