• 0

[c] Heap Question


Question

i tried really hard to avoid posting this question but i cant seem to spot the problem :(

so here it is..

basically i want to print the highest number of 'search_counts' from a heap.

> there is an array of struct HEAP

> there is only 1 element in HEAP , it is DATA *dataPtr , basically it points to a struct DATA (which has been allocated memory dynamically)

> i have to delete the top most item from the heap ary and print it and then reheapDown to get it back to a heap form.

problem: it prints all but the last element correctly. for the last element it prints out garbage. :(

i have been through the debugger so many times but yet it failed.

here is the code

int j is the count of how many elements were inserted into the heap ary

int whatFn is basically a checker to see that if the number of elements inserted was less than the HEAP_SIZE which is 7 then use j otherwise use HEAP_SIZE for the restrictor

void printHeap1 (HEAP *ary, int j, int whatFn)
{
	int i = 0;
	HEAP *pWalker, *pCur, *pLast, dataOut;

	pCur = ary;

	printf("--- 7 Most popular searches ---\n");

	if (whatFn == NOT_EQUAL)
	{
  pLast = &ary[j];
  j--;
  for (pWalker = pCur; pWalker < pLast; pWalker++)
  {
 	 if (deleteHeap (ary, &j, &dataOut) == 1)
    printToScreen (&dataOut, "heap");
 	 else
    printf("Unable to delete node\n");
  }
	}
	else
	{
  pLast = &ary[HEAP_SIZE -1];
  j--;
  for (pWalker = pCur; pWalker < pLast; pWalker++)
  {
 	 if (deleteHeap (ary, &j, &dataOut) == 1)
    printToScreen (&dataOut, "heap");
 	 else
    printf("Unable to delete node\n");
  }
	}
	return;
}

this goes to the delete heap function that is

int deleteHeap (HEAP *heap, int *last, HEAP *dataOut)
{
//	int item;

	if (*last < 0)
	{
  return 0;
	}

	dataOut->dataPtr = heap[0].dataPtr;
	heap [0].dataPtr = heap [*last].dataPtr;
//	heap[*last].dataPtr = NULL;
	(*last)--;

	reheapDown (heap, 0, *last);

	return 1;
}

this later goes to the reheapDown function which is

void reheapDown (HEAP *heap, int root, int last)
{
	DATA hold, leftKey, rightKey, largeChildKey;
	int largeChildIndex = 0;
	//int parent;

	if ((root * 2 + 1) <= last)
	{
  leftKey = *(heap [root * 2 + 1].dataPtr);

  if ((root * 2 + 2) <= last)
  {
 	 rightKey = *(heap [root * 2 + 2].dataPtr);
  }
  else
  {
 	 rightKey.search_count = -1;
  }

  if (leftKey.search_count > rightKey.search_count)
  {
 	 largeChildKey = leftKey;
 	 largeChildIndex = root * 2 + 1;
  }
  else
  {
 	 largeChildKey = rightKey;
 	 largeChildIndex = root * 2 + 2;
  }

  if (heap[root].dataPtr->search_count < heap [largeChildIndex].dataPtr->search_count)
  {
 	 hold = *(heap [root].dataPtr);
 	 heap [root].dataPtr = heap [largeChildIndex].dataPtr;
 	 heap [largeChildIndex].dataPtr = &hold;

 	 reheapDown (heap, largeChildIndex, last);
  }
	}
	return;
}

any form of help is appreciated. i just need someone to spot the error. i can fix the rest myself

thanks :)

Link to comment
https://www.neowin.net/forum/topic/52712-c-heap-question/
Share on other sites

7 answers to this question

Recommended Posts

  • 0

You like them? Geez, how masochistic is that? :D

My personal opinion is that pointers:

1. Make code practically unreadable.

2. Rarely increase performance.

3. Don't really allow you to do anything that you couldn't already do.

4. Make it easy to introduce bugs.

I'm not denying that there are situations where pointers are absolutely necessary, but for the above reasons I would rather not use them. Thankfully, C# (my language of choice) allows you to avoid using pointers altogether (unlike C and C++). It still has them, mind you, but you are heavily discouraged from using them.

:alien:

Link to comment
https://www.neowin.net/forum/topic/52712-c-heap-question/#findComment-526933
Share on other sites

  • 0

i know it sounds crazy but once u get a hang of pointers it aint that bad.. :)

i havent tried C# yet... i will be doing C++ in jan and i already know c and beginning java and a little of actionscripting..

as u know, java and actionscripting dont have pointers (well, the do have them but they are hidden)

and its all cool but i still feel i have more control with the use of pointers.. i feel C and C++ form a stronger combo than what java and its rich APIs could present :)

its just my opinion derived from my 1 yr of programming experience :)

Link to comment
https://www.neowin.net/forum/topic/52712-c-heap-question/#findComment-527998
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • FastStone Image Viewer 8.5 by Razvan Serea FastStone Image Viewer is a fast, stable, user-friendly image browser, converter and editor. It has a nice array of features that include image viewing, management, comparison, red-eye removal, emailing, resizing, cropping, retouching and color adjustments. Its innovative but intuitive full-screen mode provides quick access to EXIF information, thumbnail browser and major functionalities via hidden toolbars that pop up when your mouse touches the four edges of the screen. Other features include a high quality magnifier and a musical slideshow with 150+ transitional effects, as well as lossless JPEG transitions, drop shadow effects, image annotation, scanner support, histogram and much more. It supports all major graphic formats (BMP, JPEG, JPEG 2000, animated GIF, PNG, PCX, PSD, EPS, TIFF, WMF, ICO and TGA) and popular digital camera RAW formats (CRW, CR2, NEF, PEF, RAF, MRW, ORF, SRF, ARW, SR2, RW2 and DNG). FastStone Image Viewer features: Image browser and viewer with a familiar Windows Explorer-like user interface Support for many popular image formats and PDF viewing True Full Screen viewer with convenient image zoom support and unique fly-out menu panels Crystal-clear and customizable one-click image magnifier Powerful image editing tools: Resize/resample, rotate/flip, crop, sharpen/blur, adjust lighting/colors/curves/levels etc. Eleven re-sampling algorithms to choose from when resizing images Image color effects: gray scale, sepia, negative, Red/Green/Blue adjustment Image special effects: drop shadow, framing, bump map, sketch, oil painting, lens Draw texts, lines, highlights, rectangles, ovals and callout objects on images Clone Stamp and Healing Brush Superior red-eye effect removal/reduction with completely natural looking end result Multi-level Undo/Redo capability Single click to switch between best fit and actual size mode Image management, including file tagging, rating and drag-and-drop to copy/move/re-arrange files Histogram display with color counter feature Compare images side-by-side (up to 4 at a time) to easily cull those forgettable shots Image EXIF metadata support (plus comment editing for JPEGs) Configurable batch processing to convert/rename large or small collections of images Slideshow with 150+ transition effects and music support (MP3, WMA, WAV...) Create efficient image attachments for emailing to family and friends Print images with full page-layout control Create fully configurable contact sheets Create memorable artistic image montages from your family photos for personalized desktop wallpapers (Wallpaper Anywhere) Acquire images from scanners. Support batch scanning to PDF, TIFF, JPEG and PNG Versatile screen capture capability Powerful Save As interface to compare image quality and control generated file size Run favorite external editors with one keystroke from within Image Viewer Offer portable version of the program which can be run from a removable storage device Configurable mouse wheel support Support themes (bright, gray and dark) Support dual-monitor configurations Support touch interface (tap, swipe, pinch) Support dual instances Play video and audio files (Third party codecs may be required for old versions of Windows) And much more... FastStone Image Viewer 8.5 changelog: Added support for SVG format Added Start importing automatically and Handle duplicate file names automatically options to the Import Photos and Videos tool WebP files can now be rotated and saved with a single click Enhanced dark theme support in the PDF viewer Fixed a bug where some links in PDF files were not clickable Other improvements and bug fixes Download: FastStone Image Viewer 8.5 | Portable | ~15.0 MB (Freeware) View: FastStone Image Viewer Website | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Yup, broke my comp… again. its times like this when I regret AMD. This just never happens on NV.
    • Huh? You're delusional calling the Steam Deck dead. It is so successful that it has sold out multiple times. Even after the price hike this year it sold out again with 24 hours of being back in stock. The demand is real and has not died down even after four years.
    • Same place "Unreal III" is, in everyone's thoughts!
    • So how much water is used in that "initial charge" and how often will it need to be recharged?
  • Recent Achievements

    • Rookie
      DaviKar went up a rank
      Rookie
    • Dedicated
      HidekoYamamoto94 earned a badge
      Dedicated
    • One Month Later
      timbobit earned a badge
      One Month Later
    • One Month Later
      nates earned a badge
      One Month Later
    • Week One Done
      Almohandis earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      460
    2. 2
      +Edouard
      160
    3. 3
      PsYcHoKiLLa
      110
    4. 4
      Michael Scrip
      86
    5. 5
      Steven P.
      69
  • Tell a friend

    Love Neowin? Tell a friend!