簡體   English   中英

簡單的指針算法不起作用?

[英]Simple pointer arithmetic not working?

char * str = "Hello";

*(str+1) = '3';

cout<<str;

我在那里嘗試做的是將第二個字符更改為“ 3”,將其轉換為H3llo

為什么不起作用?

這是未定義的行為。 您不能更改文字。

要具有指向文字的指針,它應該是:

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

然后,為了能夠更改字符串,例如

char str[] = "Hello";

另一個選擇是動態分配內存(使用mallocfree

字符串文字是在只讀存儲器中分配的,因此基本上它們是類型( const char * ),不能更改。 另請參閱以獲取更多信息。

因為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

這里的事情是我在設置字符串中的char之前分配了內存。 但是,如果您對分配不滿意,可以隨時設置char str [] =“ hello”;

str內存將在.rodata節中分配。 因此嘗試修改只讀數據將產生問題。

以下問題給問題。

#include <stdio.h>

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

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


return 0;
}

相應的拆卸

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

結果是

Hello 
Segmentation fault (core dumped)

我在X86_64上使用gcc版本4.6.3(Ubuntu / Linaro 4.6.3-1ubuntu5)。

str是一個指向字符串常量的指針,該字符串的內存在只讀節中分配。 如果您嘗試修改字符串內容,則結果不確定。 但是,與始終綁定到相同內存位置的數組名稱相比,您可以修改指針以指向其他內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM