user1091856
user1091856

Reputation: 3158

Simple pointer arithmetic not working?

char * str = "Hello";

*(str+1) = '3';

cout<<str;

What I was trying to do there was to change the second character into '3', turning it into H3llo

Why doesn't it work?

Upvotes: 0

Views: 179

Answers (6)

Manish
Manish

Reputation: 2327

str is a pointer to string constant and memory for the string is allocated in read-only section . If u try to modify the string content the result is undefined. However you can modify the pointer to point something else as compared to an array-name which is always bound to same memory location.

Upvotes: 0

Jeyaram
Jeyaram

Reputation: 9474

Memory for str will be allocated in .rodata section. so trying to modify read only data will produce problem.

The following problem gives issue.

#include <stdio.h>

int main()
{
char * str = "Hello";

printf("\n%s \n", str);
*(str+1) = '3';
printf("\n%s \n", str);


return 0;
}

corresponding dis-assembly

 .file   "dfd.c"
        .section        .rodata
.LC0:
        .string "Hello"
.LC1:
        .string "\n%s \n"
        .text
  .....
  .....

And the result is

Hello 
Segmentation fault (core dumped)

Im using gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5) on X86_64.

Upvotes: 0

C404
C404

Reputation: 243

#include <string.h>
char *str;
if((str = malloc(strlen("hello"))) != NULL)
  return (null);
str = strcpy(str, "hello");
printf("%s\n", str); // should print hello
str[2] = '3';
printf("%s\n", str) // should print he3lo

The thing here is that i allocate memory before to set char in the string. But if you're not good with allocation you can always set the char str[] = "hello";

Upvotes: 0

Kiril Kirov
Kiril Kirov

Reputation: 38153

This is undefined behaviour. You cannot change literal.

To have a pointer to literal, it should be:

  const char* str = "Hello";
//^^^^^

Then, to be able to change string, this should be, for example

char str[] = "Hello";

The other option is to allocate dynamically the memory (using malloc and free)

Upvotes: 3

Vijay
Vijay

Reputation: 67211

string literals are allocated in read only memory.so basically they are of type(const char *).It cannot be changed. Also see this for more information.

Upvotes: 2

Yang
Yang

Reputation: 777

Because str is of type "const char *" and you are not allowed to overwrite the object it points to.

Upvotes: 1

Related Questions