[英]Segmentation fault: 11 while copying one array to another
我想將所有內容從buf[rm]
復制到temp_a
並打印temp_a
但出現分段錯誤:運行11。 我需要在程序中進一步使用key[]
。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int main()
{
int c = 0, rm;
int i;
int iter;
int j = 0;
int temp;
int temp_a;
for (int i = 0; i < 10000; i++)
{
char buf[32];
for (int rm = 0; rm < 32; rm++)
{
buf[rm] = rand();
strcpy(temp_a,buf[rm]);
key[] = temp_a;
printf("%d\n",key[] );
}
}
}
您已經聲明了int temp_a;
因此temp_a
是一個具有固定大小的int
變量,您正嘗試將字符串復制到其中。 在開始編碼之前,請閱讀C中的所有數據類型並正確理解。 還請閱讀有關數組以及它們與其他變量類型的不同之處。 您必須將您的temp_a
變量聲明為char temp_a[32];
或諸如char *temp_a = malloc(32);
動態內存分配char *temp_a = malloc(32);
您需要進行以下修改:-
for (int i = 0; i < 10000; i++)
{
int buf[32];// this should be a int array
for (int rm = 0; rm < 32; rm++)
{
buf[rm] = rand();// rand returns integer
temp_a = buf[rm]);
key[rm] = temp_a;
printf("%d\n",key[rm] );
}
}
哇,這里發生了很多錯誤。
strcpy函數用於將終止的字符串復制到緩沖區位置。 您將int temp_a指定為目標,因此適合的最大字符數為4。但是,您將buf [32]聲明為未初始化,並且strcpy需要使用終止的字符串作為源。 該函數無法找到終止字符,因此它僅寫入temp_a的邊界。
您沒有足夠的內存“分配”用於嘗試分配給key []的條目。 請注意,您需要事先告訴編譯器應該准備什么樣的數據(內存大小)。 分段錯誤告訴您,您正在嘗試適應沒有足夠內存保留的數據。
根據ypu想要分配的數據,在這種情況下,malloc()將幫助您保留必要的內存,以便在您尋求效率時進行保留。 否則,您需要聲明等效數組以存儲所有條目。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.