البرمجة

كيفية حذف مصفوفة في C++

In C++, when you use new[] to allocate an array dynamically, you should use delete[] to deallocate it. However, in your code, you have incremented the pointer p before deleting the array, which is incorrect. Here’s the corrected version:

cpp
int *p = new int[3]; *p = 1; p++; *p = 2; p--; delete[] p;

When you allocate memory for an array using new[], the pointer p points to the first element of the array. If you increment p, it will point to the second element, and if you decrement p, it will point back to the first element. So, before deleting the array, you need to decrement p to make it point back to the beginning of the array.

Also, note that in this example, you’re deleting an array that contains only two elements (1 and 2), not three. If you want to delete the entire array, you should allocate memory for three elements and only then populate the array.

المزيد من المعلومات

في لغة C++، عندما تقوم بإنشاء مصفوفة باستخدام العامل new[]، يجب عليك استخدام العامل delete[] لحذف المصفوفة بشكل صحيح. العملية الصحيحة لحذف المصفوفة في الشيفرة التي قدمتها تكون على النحو التالي:

cpp
int *p = new int[3]; // تخصيص مصفوفة من 3 عناصر *p = 1; // تعيين القيمة 1 لأول عنصر في المصفوفة p++; // نقل المؤشر ليشير إلى العنصر الثاني في المصفوفة *p = 2; // تعيين القيمة 2 للعنصر الثاني في المصفوفة p--; // إعادة المؤشر ليشير إلى العنصر الأول في المصفوفة delete[] p; // حذف المصفوفة

ومن الجدير بالذكر أن استخدام delete[] يحذف المصفوفة بأكملها، لذا من الأفضل عدم تحريك المؤشر p بعد تعيين القيم في المصفوفة، واستخدامه كمؤشر إلى بداية المصفوفة عند استخدام delete[] لضمان حذف المصفوفة بشكل صحيح.

مقالات ذات صلة

زر الذهاب إلى الأعلى
إغلاق

أنت تستخدم إضافة Adblock

يرجى تعطيل مانع الإعلانات حيث أن موقعنا غير مزعج ولا بأس من عرض الأعلانات لك فهي تعتبر كمصدر دخل لنا و دعم مقدم منك لنا لنستمر في تقديم المحتوى المناسب و المفيد لك فلا تبخل بدعمنا عزيزي الزائر