![](/img/trans.png)
[英]Why when i'm using strcpy in struct are copying everything to the same variable - c language
[英]Why does the program stop if I'm using strcpy() on two strings with the exact same size in C?
我使用 Windows 的 CodeBlocks 作為我的 IDE。 在這個程序中,我試圖復制兩個不同的字符串(string[8][0] 和 string[9][0]),但我不能,即使它們的長度完全相同。 我不明白為什么該程序不起作用,因為當我在練習中使用兩個長度相同的不同字符串時,程序起作用了。
#include <stdio.h>
#include <string.h>
int main()
{
char* string[10][10];
int i;
string[8][0] = "ooo";
string[9][0] = "uuu";
puts(string[8][0]);
puts(string[9][0]);
printf("%d %d", strlen(string[8][0]), strlen(string[9][0]));//This line is just to make sure that both strings have the same lenght
strcpy(string[8][0], string[9][0]);//I want to copy the content of the string "string[9][0]" to the string "string[8][0]" and replace what was on that string
puts(string[8][0]);
puts(string[9][0]);
return 0;
}
您所看到的是未定義的行為1 。 為什么? 因為行string[8][0] = "ooo";
將常量字符串文字的地址分配給string[8][0]
處的指針。 然后,當您稍后調用strcpy(string[8][0], string[9][0]);
,您正在嘗試寫入該常量數據。
使您的程序工作的“快速修復”是將字符串文字復制到非常量 char 數組中,如下所示:
int main()
{
char* string[10][10];
int i;
// string[8][0] = "ooo";
char buffer[4] = "ooo"; // This line COPIES the literal into the non-const array
string[8][0] = buffer; // ... and here we give the pointer that array's address
string[9][0] = "uuu";
puts(string[8][0]);
puts(string[9][0]); // Note, I've added a newline below to make the output tidier!
printf("%d %d\n", strlen(string[8][0]), strlen(string[9][0]));//This line is just to make sure that both strings have the same lenght
strcpy(string[8][0], string[9][0]);//I want to copy the content of the string "string[9][0]" to the string "string[8][0]" and replace what was on that string
puts(string[8][0]);
puts(string[9][0]);
return 0;
}
1在某些平台上,未定義的行為可能導致發生任意數量的事情; 該程序可能會默默地“忽略”您在我的平台上覆蓋常量數據的嘗試。 程序崩潰(就像你的那樣)。
關於
string[8][0] = "ooo";
和類似的陳述:
該代碼將一個點復制到只讀 memory
請記住,只讀 memory 不能被程序更改。
建議修改代碼,以便將字符串實際放置在數組中,類似於。
char string[10][10];
...
strcpy( string[0], "ooo" );
關於:
printf("%d %d\n", strlen(string[8][0]), strlen(string[9][0]));
function: strlen()
返回size_t
,而不是int
所以 output 格式轉換的說明符應該是%zu
而不是%d
如果您的編譯器沒有警告您代碼中的問題,則啟用警告然后修復這些警告。
對於gcc
,至少使用: -Wall -Wextra -Wconversion -pedantic -std=gnu11
請注意,其他編譯器使用不同的選項來產生相同的結果
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.