範例顯示了傳遞數組作爲參數處理陣列
#include <iostream>
#include <malloc.h>
using namespace std;
typedef unsigned char U8;
#define MAX_LEN 20
void func1(U8* arr)
{
printf(" Passing Base address Element1 = %s\n",arr);
}
void func2(U8* arr)
{
printf(" Passing Pointer address Element1 = %s \n",arr);
}
int main()
{
U8 arr[MAX_LEN] = "Stack Overflow\n";
U8* arr1 = (U8*)malloc(sizeof(MAX_LEN));
func1(arr); /* Passing Base address */
memcpy(arr1,arr,sizeof(arr));
/*
memcpy(arr1,arr,sizeof(MAX_LEN)); Leads to Heap Corruption why ?
*/
func2(arr1);/* Passing pointer */
free(arr1);
cout << "Array Freed" << endl;
cin.get();
return 0;
}
查詢: 1.這是在考慮最佳的實踐與數據處理 2.請提出可靠的方法[於堆棧或堆數據]要用於這樣的情況下
請勿使用''。這不是你的想法。 –
將c與C++混合通常不是一個好主意。 –
你是用C還是用C++寫的?如果你正在編寫C++代碼,我強烈建議使用像std :: vector或std :: array這樣的標準容器來代替手工製作的指針/ malloc/free-gymnastics。 – MadScientist