問題陳述
我想寫一個函式
int *concat_tab(int n1, int *t1, int n2, int *t2)
在執行以下操作的純 C 中:給定兩個整數陣列(作為指標),該函式應回傳一個新陣列,該陣列是兩個輸入陣列的串聯。
輸入名稱的含義如下:
n1: 第一個陣列的長度;*t1: 指向第一個陣列的第一個元素的指標;n2: 第二個陣列的長度;*t2: 指向第二個陣列的第一個元素的指標。
我的代碼
#include<stdio.h>
#include<stdlib.h>
int *concat_tab(int n1, int *t1, int n2, int *t2){
/*
* Takes two 1D arrays and their lengths as input and outputs their concatenation.
* Input:
* - n1: Length of first array
* - t1: First array
* - n2: Length of second array
* - t2: Second array
* Output:
* - Array of length n1 n2 containing the elements of t1 followed by the elements of t2
*/
int *output = (int*) malloc(n1 n2);
for(int k = 0; k < n1 n2; k ){
if(k < n1) {
*(output k) = *(t1 k);
}
else{
*(output k) = *(t2 k-n1);
}
}
return output;
}
int main(){
int array1[4] = {1, 2, 3, 4};
int array2[5] = {10, 11, 12, 13, 14};
int *output = concat_tab(4, array1, 5, array2);
for(int k = 0; k < 9; k ){
printf("Output[%d] = %d\n", k, *(output k));
}
return 0;
}
我的問題
作為輸出,我根據需要得到
Output[0] = 1
Output[1] = 2
Output[2] = 3
Output[3] = 4
Output[4] = 10
Output[5] = 11
Output[6] = 12
Output[7] = 13
Output[8] = 14
但是,我的程式以退出代碼 -1073740940 而不是 0 退出。為什么會發生這種情況?
uj5u.com熱心網友回復:
發生不需要的退出代碼是因為傳遞給mallocC 中的輸入表示將在記憶體中分配的位元組數(通常不等于陣列的長度)(例如,int陣列中的每個需要 4 個位元組而不僅僅是 1)。
因此,發生的情況是 C 為output陣列分配的記憶體太少。這可以通過更換線路來解決
int *output = (int*) malloc(n1 n2);
和
int *output = (int*) malloc(sizeof(int)*(n1 n2));
現在程式將根據需要退出。
uj5u.com熱心網友回復:
這個記憶體分配
int *output = (int*) malloc(n1 n2);
相當于
int *output = (int*) malloc( ( n1 n2 ) * sizeof( char ));
但是您需要為 int 型別的物件分配記憶體。那是你需要寫
int *output = (int*) malloc( ( n1 n2 ) * sizeof( int ) );
函式宣告也不好。首先,傳遞的陣列不會在函式內更改。所以對應的引數應該有限定符const。
其次,指定陣列中元素數量的引數應該具有型別size_t。
第三,引數的順序應該改變。
所以函式宣告應該看起來像
int * concat_tab( const int *t1, size_t n1, const int *t2, size_t n2 );
注意要檢查記憶體是否分配成功。當不再需要分配的陣列時,您需要釋放它。
這里顯示了您的程式的外觀。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int * concat_tab( const int *t1, size_t n1, const int *t2, size_t n2 )
{
int *output = NULL;
if (n1 || n2)
{
output = malloc( ( n1 n2 ) * sizeof( int ) );
if (output != NULL)
{
memcpy( output, t1, n1 * sizeof( int ) );
memcpy( output n1, t2, n2 * sizeof( int ) );
}
}
return output;
}
int main( void )
{
int array1[] = { 1, 2, 3, 4 };
size_t n1 = sizeof( array1 ) / sizeof( *array1 );
int array2[] = { 10, 11, 12, 13, 14 };
size_t n2 = sizeof( array2 ) / sizeof( *array2 );
int *output = concat_tab( array1, n1, array2, n2 );
if ( output != NULL )
{
for (size_t i = 0; i < n1 n2; i )
{
printf( "Output[%zu] = %d\n", i, *( output i ) );
}
}
free( output );
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/397322.html
