简体   繁体   English

简单的指针算法不起作用?

[英]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 我在那里尝试做的是将第二个字符更改为“ 3”,将其转换为H3llo

Why doesn't it work? 为什么不起作用?

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 ) 另一个选择是动态分配内存(使用mallocfree

string literals are allocated in read only memory.so basically they are of type( const char * ).It cannot be changed. 字符串文字是在只读存储器中分配的,因此基本上它们是类型( const char * ),不能更改。 Also see this for more information. 另请参阅以获取更多信息。

因为str的类型为“ const char *”,所以您不能覆盖它指向的对象。

#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. 这里的事情是我在设置字符串中的char之前分配了内存。 But if you're not good with allocation you can always set the char str[] = "hello"; 但是,如果您对分配不满意,可以随时设置char str [] =“ hello”;

Memory for str will be allocated in .rodata section. str内存将在.rodata节中分配。 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. 我在X86_64上使用gcc版本4.6.3(Ubuntu / Linaro 4.6.3-1ubuntu5)。

str is a pointer to string constant and memory for the string is allocated in read-only section . str是一个指向字符串常量的指针,该字符串的内存在只读节中分配。 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. 但是,与始终绑定到相同内存位置的数组名称相比,您可以修改指针以指向其他内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM