Simple question

This is a discussion on Simple question within the C Programming forums, part of the General Programming Boards category; I have my code written for a heap sort program and for some reason the thing that is throwing it ...

  1. #1
    Registered User
    Join Date
    Apr 2003
    Posts
    88

    Simple question

    I have my code written for a heap sort program and for some reason the thing that is throwing it off is counter variable

    Code:
    int z = 0;
    printf("z = %d",z);
    for some reason this is printing out 01244236
    Also when I change the line that these commands appear on the number is different
    Does anyone have any suggestions on what might be affecting this?

  2. #2
    .
    Join Date
    Nov 2003
    Posts
    307
    1. you need to show more code - what you show will not break anything - assuming that is a zero and not an uppercase letter 'o'

    2. It sounds like you have assigned an address to a variable that isn't a pointer. Is the compiler giving you warnings? What you describe gives you exactly the symptom you are complaining about.

  3. #3
    Registered User
    Join Date
    Apr 2003
    Posts
    88
    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <memory.h>
    #include <ctype.h>
    #include <sys/types.h>
    #include <io.h>
    #include <time.h>
    
    typedef struct 
    {
    	char name[30];
    	int position;
    	int file_choice;
    }CSV;
    
    typedef struct List
    {
    	char city[50];
    	char zipcode[8];
    	char state[2];	
    	double latitude;
    	double longitude;
    	long population;
    	struct List *next;
    	struct List *previous;
    }List_node;
    
    typedef struct
    {
    	struct List *psHead;
    	struct List *psTail;
    	struct List psCurrent;
    	int node_count;
    }List_Header;
    
    typedef struct heap
    {
    	int ipriority;
    	char city[50];
    	char state[2];
    	char zipcode[7];
    	double longitude;
    	double latitude;
    	long population;
    }heap_node;
    
    typedef struct
    {
    	struct List *psHead;
    	struct List *psTail;
    	int node_count;
    }Header;
    
    int main()
    {
    	//pointers
    	CSV *file_info;
    	heap_node *node_ptr, *heaptemp;
    	List_node *psnew, *pscurrent;
    	Header *psList;
    	List_Header *List;
    
    
    	//declarations of functions and variables
    	int choice;
    	int Main_Menu(int);
    	int Select_File(CSV *file_info, heap_node *node_ptr, heap_node *heaptemp, Header *psList,List_node *psnew, List_node *pscurrent, List_Header *List);
    	int Create_List(CSV *file_info, heap_node *node_ptr, heap_node *heaptemp, Header *psList,List_node *psnew, List_node *pscurrent, List_Header *List, FILE *readfile);
    	int Create_Heap(CSV *file_info, heap_node *node_ptr, heap_node *heaptemp, Header *psList,List_node *psnew, List_node *pscurrent, List_Header *List);
    	int ReHeapUp(heap_node *node_ptr, heap_node *heaptemp, Header *psList, int heap_count);
    	int ReHeapDown(heap_node *node_ptr, heap_node *heaptemp, Header *psList, int heap_count);
    	
    	//Memory Allocation
    	file_info = (CSV*) malloc(sizeof(CSV));
    	node_ptr = (heap_node*) malloc(sizeof(heap_node)*600);///changed this
    	psnew = (List_node*) malloc(sizeof(List_node));
    	pscurrent = (List_node*) malloc(sizeof(List_node));
    	heaptemp = (heap_node*) malloc(sizeof(heap_node));
    	psList = (Header*) malloc(sizeof(Header));
    	List = (List_Header*) malloc(sizeof(List_Header));
    
    	while(choice != 6)
    	{
    		choice = Main_Menu(choice);
    		switch(choice)
    		{
    		case 1:
    			//Select File
    			Select_File(file_info, node_ptr,heaptemp, psList,psnew, pscurrent, List);
    			break;
    		case 2:
    			//Remove largest pop
    			printf("%s",&node_ptr[0].city);//print test
    			break;
    		case 3:
    			//display summary data
    			break;
    		case 4:
    			//save summary data
    			break;
    		case 5:
    			//Reset
    			break;
    		case 6:
    			//Exit
    			break;
    		}
    	}
    	return 0;
    }
    //
    //Main_Menu prompts the user to choose one of the 6 options
    //
    int Main_Menu(int choice)
    {
    	printf("                  Heap Sort               \n");
    	printf("\n*******************************************************");
    	printf("\n      Please choose an option from the list below\n");
    	printf("\n		1. Select and read a .CSV file ");
    	printf("\n		2. Remove largest Population node from the Heap");
    	printf("\n		3. Display summary data");
    	printf("\n		4. Save summary data");
    	printf("\n		5. Reset data");
    	printf("\n		6. Exit\n");
    	printf("\n Choose an option by number<1-6>");
    	scanf("%d",&choice);
    	system("cls");
    	
    	return choice;
    }/*end Main_menu()*/
    int Select_File(CSV *file_info, heap_node *node_ptr, heap_node *heaptemp, Header *psList,List_node *psnew, List_node *pscurrent, List_Header *List)
    {
    	struct _finddata_t c_file;
    	long hFile;
    	char path_name[256];
    	int counter = 2;
    	FILE *readfile;
    
    	/* Finds first file in current directory */
        if( (hFile = _findfirst( "*.csv", &c_file )) == -1L )
    	{
    		printf( "No *.csv files in current directory!\n" );
    		printf("Enter full path and file name");
    		scanf("%s",&path_name);
    	}//end if
    	
    	else
    	{
    		printf( "Listing of .csv files in current directory\n\n" );
    		printf( "******************************************");         
    		printf( "\nFilename        \n", ' ' );
    		printf( "------       \n", ' ' );
    		printf("1. %-12s\n", c_file.name);
    		file_info[1].position = 1;
    		strcpy(file_info[1].name, c_file.name);
    		
    		
    		/* Find the rest of the files */
    		while( _findnext( hFile, &c_file ) == 0 )
    		{	
    			printf("%d. %-12s\n", counter, c_file.name);
    			file_info[counter].position = counter; 
    			strcpy(file_info[counter].name, c_file.name);
    			counter++;
    			
    		}//end while
    		
    		printf("%d. Enter a full path and file name", counter);
    		_findclose( hFile );
    	}//end else
    	
    	
    	scanf("%d",&file_info->file_choice);   
    	system("cls");
    	
    	if(file_info->file_choice == counter)
    	{
    		printf("Enter full path and file name");
    		scanf("%s",&path_name);
    		
    	}//end if
    	else
    	{
    		strcpy(path_name, file_info[file_info->file_choice].name);
    	}
    	readfile = fopen(path_name,"r");
    	if(readfile == NULL)
    	{
    		printf("\nfile could not be opened\n\n");
    		main();
    	
    	}
    	else
    	{
    		
    		printf("\nLoading\n");
    		Create_List(file_info, node_ptr, heaptemp, psList,psnew, pscurrent, List, readfile);	
    		Create_Heap(file_info, node_ptr, heaptemp, psList,psnew, pscurrent, List);
    		system("cls");
    		
    	}
    	return 0;
    }
    //
    //
    //Create_List creates a linked list
    //that is then used to create a binary tree
    int Create_List(CSV *file_info, heap_node *node_ptr, heap_node *heaptemp, Header *psList,List_node *psnew, List_node *pscurrent, List_Header *List, FILE *readfile)
    {
    	char line[100], long_temp[25], lat_temp[25], pop_temp[25];
    	int z = 0;
    
    	printf("z = %d",z);
    	while ( fgets(line,100,readfile) != NULL ) 
    	{
    		psnew = malloc(sizeof(struct List));
    		strcpy(psnew->city, strtok(line,","));
    		strcpy(psnew->state, strtok(NULL,","));
    		strcpy(psnew->zipcode, strtok(NULL,","));
    		strcpy(long_temp, strtok(NULL,","));
    		psnew->longitude = atof(long_temp);
    		strcpy(lat_temp, strtok(NULL,","));
    		psnew->latitude = atof(lat_temp);
    		strcpy(pop_temp, strtok(NULL,","));
    		psnew->population = atol(pop_temp);
    		
    		if (z == 0)
    		{
    			List->psHead = psnew;
    			psnew->previous = NULL;
    			psnew->next = pscurrent;
    			pscurrent->previous = psnew;
    		}
    		else
    		{
    			psnew->next = pscurrent;
    			psnew->previous = pscurrent->previous;
    			psnew->next->previous = psnew;
    			psnew->previous->next = psnew;
    		}
    		z++;//node_count was initialized to 0
    		//printf("%d",&node_count);
    	}
    	List->psTail = psnew;
    	List->node_count = z;
    	fclose(readfile);
    	//strcpy(data->time, asctime(localtime(&timer)));
    	//system("cls");
    	return 0;
    }
    //
    int Create_Heap(CSV *file_info, heap_node *node_ptr, heap_node *heaptemp, Header *psList,List_node *psnew, List_node *pscurrent, List_Header *List)
    {
    	int x, y = 0,counter, heap_count = 0;
    	pscurrent = List->psHead;
    	counter = List->node_count;
    	//heap_count is number of nodes currently in heap
    	printf("%d",&counter);
    	while(counter != 0)//goes until no nodes are left
    	{
    		//node_ptr = realloc(node_ptr, sizeof(heap_node)*16);//is this right
    		for(x = 0;x<16;x++)
    		{
    			if(psList->node_count == 0)//if no nodes exist
    			{
    				node_ptr->ipriority = 0;
    				strcpy(node_ptr[0].city, pscurrent->city);
    				strcpy(node_ptr[0].zipcode, pscurrent->zipcode);
    				strcpy(node_ptr[0].state, pscurrent->state);
    				node_ptr[0].latitude = pscurrent->latitude;
    				node_ptr[0].longitude = pscurrent->longitude;
    				node_ptr[0].population = pscurrent->population;
    			}
    			else
    			{
    				node_ptr->ipriority = heap_count;
    				strcpy(node_ptr[heap_count].city, pscurrent->city);
    				strcpy(node_ptr[heap_count].zipcode, pscurrent->zipcode);
    				strcpy(node_ptr[heap_count].state, pscurrent->state);
    				node_ptr[heap_count].latitude = pscurrent->latitude;
    				node_ptr[heap_count].longitude = pscurrent->longitude;
    				node_ptr[heap_count].population = pscurrent->population;
    				ReHeapUp(node_ptr,heaptemp, psList, heap_count);
    
    			}
    			pscurrent = pscurrent->next;
    			free(pscurrent->previous);
    			counter--;
    			heap_count++;
    			
    		}
    	}
    	
    	system("cls");
    	return 0;
    }
    //
    //
    //
    int ReHeapUp(heap_node *node_ptr, heap_node *heaptemp, Header *psList, int heap_count)
    {
    	int x;
    	for(x = heap_count;x > 0;x--)
    	{
    		if(node_ptr[x].population > node_ptr[(x-1)/2].population)
    		{
    			//if child is bigger than parent
    			strcpy(heaptemp->city, node_ptr[x].city);
    			strcpy(node_ptr[x].city, node_ptr[(x-1)/2].city);
    			strcpy(node_ptr[(x-1)/2].city, heaptemp->city);
    			
    			strcpy(heaptemp->zipcode, node_ptr[x].zipcode);
    			strcpy(node_ptr[x].zipcode, node_ptr[(x-1)/2].zipcode);
    			strcpy(node_ptr[(x-1)/2].zipcode, heaptemp->zipcode);
    
    			strcpy(heaptemp->state, node_ptr[x].state);
    			strcpy(node_ptr[x].state, node_ptr[(x-1)/2].state);
    			strcpy(node_ptr[(x-1)/2].state, heaptemp->state);
    
    			heaptemp->latitude = node_ptr[(x-1)/2].latitude;
    			node_ptr[(x-1)/2].latitude = node_ptr[x].latitude;
    			node_ptr[x].latitude = heaptemp->latitude;
    
    			heaptemp->longitude = node_ptr[(x-1)/2].longitude;
    			node_ptr[(x-1)/2].longitude = node_ptr[x].longitude;
    			node_ptr[x].longitude = heaptemp->longitude;
    
    			heaptemp->population = node_ptr[(x-1)/2].population;
    			node_ptr[(x-1)/2].population = node_ptr[x].population;
    			node_ptr[x].population = heaptemp->population;
    
    			heaptemp->ipriority = node_ptr[(x-1)/2].ipriority;
    			node_ptr[(x-1)/2].ipriority = node_ptr[x].ipriority;
    			node_ptr[x].ipriority = heaptemp->ipriority;
    		}
    	}
    	return 0;
    }
    //
    //
    //
    int ReHeapDown(heap_node *node_ptr, heap_node *heaptemp, Header *psList, int heap_count)
    {
    	return 0;
    }

  4. #4
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,765
    The first step would be to
    a) write it in C - the // comments and the malloc casts really give the game away that's it's probably C++

    b) Cut out all of the non-ANSI header files
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <memory.h>
    #include <ctype.h>
    #include <sys/types.h>
    #include <io.h>
    #include <time.h>

    You really cut down on the number of people who can help you.

    > file_info[1].position = 1;
    > strcpy(file_info[1].name, c_file.name);
    Arrays start at 0, not 1
    Since you only appear to allocate a single CSV, this is out of bounds.
    I'd check all your other array accesses
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  5. #5
    Registered User
    Join Date
    Apr 2003
    Posts
    88
    what makes this code c++?
    you can't cast malloc in C?

    Also which headers should be removed?

    The CSV struct is only there to locate all .csv files in the current directory so the user can choose one, later on the source file that was chosen is reported back to the user

    and the problem is not with that, because all .csv files in that folder were found, I can also choose a source file and read it in fine.

    After that the contents are supposed to be read into a linked list. The problem is that after I initialize the counter to 0,the one that is used to count the number of records that are read in. I run a print test and it reads "01244236"

  6. #6
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,765
    > what makes this code c++?
    The // comments

    > you can't cast malloc in C?
    Sure you can - but it is at best a waste of effort, and at worst it hides a potential bug
    The FAQ explains this
    http://faq.cprogramming.com/cgi-bin/...&id=1043284351

    > Also which headers should be removed?
    Try
    #include <memory.h>
    #include <sys/types.h>
    #include <io.h>


    > printf("\nfile could not be opened\n\n");
    > main();

    Something else I've spotted - recursive calls to main() are not allowed.
    This goes a long way to explain why all your data gets trashed.
    Just do a
    return 0;
    or something so it goes round the while loop again.

    > and the problem is not with that,
    If 'A' overwrites 'B', then 'A' appears to work and 'B' doesn't. So simply saying 'A' works isn't good enough.
    You'll need to fix the array bound problem at some point, so you may as well do it now.

    > Select_File(file_info, node_ptr,heaptemp, psList,psnew, pscurrent, List);
    I bet if you change this to
    Code:
    printf( "Node=%p\n", node_ptr );
    Select_File(file_info, node_ptr,heaptemp, psList,psnew, pscurrent, List);
    printf( "Node=%p\n", node_ptr );
    You'll find that you're not returning a modified list.

    > strcpy(psnew->state, strtok(NULL,","));
    If you run out of commas in your line, strtok() will return NULL, and strcpy() will blow up.

    Can you attach a sample of your CSV file?
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  7. #7
    Registered User
    Join Date
    Apr 2003
    Posts
    88
    The // comments appear as comments when I write them

    Ok, I took out those header files, but now I don't have a way to search for files in the current directory.

    I also changed the calls to main() to return 0;

    I have attached a .csv file, just change the extension to .csv
    Attached Files Attached Files

  8. #8
    Registered User
    Join Date
    Apr 2003
    Posts
    88
    sorry it won't let me post .csv files and the data gets lost in the process

  9. #9
    Registered User
    Join Date
    Sep 2003
    Posts
    135
    Originally posted by Salem
    > what makes this code c++?
    The // comments
    No, those are valid comments in C and have been since the standard was revised in 1999.

  10. #10
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,765
    And you have a C99 compiler?

    >sorry it won't let me post .csv files and the data gets lost in the process
    Put them in a zip file then
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  11. #11
    Registered User
    Join Date
    Apr 2003
    Posts
    88
    here are the csv files
    Attached Files Attached Files

  12. #12
    Registered User
    Join Date
    Sep 2003
    Posts
    135
    Originally posted by Salem
    And you have a C99 compiler?
    Who cares? The C language is defined by the ISO standard, not by whichever compiler I happen to use. Compiler support for C99 is pretty good these days.

  13. #13
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Originally posted by Omnius
    Who cares? The C language is defined by the ISO standard, not by whichever compiler I happen to use. Compiler support for C99 is pretty good these days.
    You're joking right? Half of the people here use "Turbo C 3.0".

    Quzah.
    Hope is the first step on the road to disappointment.

  14. #14
    .
    Join Date
    Nov 2003
    Posts
    307
    We use C99 compliant compilers - we are also a production shop.
    Consider using qsort() instead of writing a heapsort or whatever.
    Each sorting algorithm is best suited for certain types of data -
    for example: a bubble sort is the fastest algorithm for data that has only one or two items out of place by one position.

    qsort() is good because it is all-around reasonably good, although for some situations there are better approaches. When you can't anticpate your data stream every time use qsort().
    Or production code takes a second parameter - the sort field.
    We have an array of "comp" functions that are dynamically selected - so that's why we opted for qsort() because we needed an all-around decent performer, and none of the datasets exceeds 10000 items.
    Code:
    /* sample.c from code snippets we use for the exact same purpose sorting 
                tab-delimited files qsort() is generally more efficient */
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #define DELIMITER ","                          /* token separator */
    #define ARR_SIZE 2500                          /* largest possible number of records */
    #define BUFSZ 256                              /* char in read buffer */
    #define CITYSZ 23                              /* longest USPS allows in addresses +1 */
    #define FLDS 6                                 /* fields in struct */
    
    typedef struct {
           char city[CITYSZ];
           char state[3];
           char zip[6];
           char lat[8];
           char lng[8];
           char population[9];
    } rec;
    void check(int);           
    int comp(void *, void *);
    void parse(char *, rec *,int *);
    void tst(FILE *);
    void createoffsets(int *,rec *);
    void printit(rec *,int);
    
    int main(int argc, char *argv[]){
    	FILE *in=NULL;
    	char tmp[BUFSZ]={'\0'};
    	rec records[ARR_SIZE];
    	rec *ptr=records;
    	int count=0;
    	int offset[7]={0};
    	tst(in=fopen(argv[1],"r"));	
    	createoffsets(offset,ptr);
    	while(!feof(in)){
    	     memset(tmp,0x00,sizeof(tmp));
    	     if(fgets(tmp,BUFSZ-1,in)!=NULL){
    	      	  parse(tmp,ptr++,offset);
    	      	  check(count++);
    	     } 	  
    	}
    	if(fclose(in)==EOF){
    		perror("Error on input file");
    		exit(EXIT_FAILURE);
    	}
    	qsort(records,count,sizeof(records[0]),comp);
    	printf("records found:%d\n",count);
    	printit(records,count);
    	return 0;
    }
    void tst(FILE *test){                                   /* check on file open */
    	if (test==NULL){
    	    perror("Error opening file");
    	    exit(EXIT_FAILURE);
    	}
    }
    void parse(char *tmp, rec *recptr, int *offset){       /* whack string into struct fields */
    	  char *fmt[FLDS+1]={"%22s","%2s","%5s","%6s","%6s","%8s",""};
    	  int i=0,   *local=offset;
              char *buf, **fmtptr=fmt;
              buf=strstr(tmp,"\n");
              if(buf)*buf=0x00;
              memset(recptr,0x00,sizeof(rec));
              for(buf=strtok(tmp,DELIMITER); 
                  buf!=NULL;
                  buf=strtok(NULL,DELIMITER),local++,fmtptr++){
                       sprintf(recptr->city + *local,*fmtptr,buf);                  
              }
    }
    void printit(rec *recs, int count){                /* dump array of structs */
    	  rec *local;
    	  int i=1;
              printf("%d records found, sorted by population size:\n",count);
              for(local=recs;count;count--,local++)	
                 printf("%22s %2s %8s\n",                   
                        local->city,
                        local->state,
                        local->population);
    }
    int comp(void *c, void *d){                          /* function for qsort */
    	rec *a, *b;
    	a=(rec *)c;
    	b=(rec *)d;
    	return strcmp(a->population,b->population );
    }
    void createoffsets(int *values, rec *recptr){       /* create pointer offsets for struct */
         char *base=recptr->city;     
         char *buf=recptr->state;	
         *values++=0;     
         *values++=(int)buf - (int)base;
         buf=recptr->zip;
         *values++=(int)buf - (int)base;
         buf=recptr->lat;
         *values++=(int)buf - (int)base;
         buf=recptr->lng;
         *values++=(int)buf - (int)base;
         buf=recptr->population;
         *values=(int)buf - (int)base;
    }
    void check(int count){                              /* check array bounds */
         if( ARR_SIZE +1 == count){                     /* change this to whatever you need */
                printf("Maximum possible number of records read in, aborting\n");
                exit(EXIT_FAILURE);                     /* puke before we core dump */
         }	
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Simple question regarding variables
    By Flakster in forum C++ Programming
    Replies: 10
    Last Post: 05-18-2005, 09:10 PM
  2. Simple class question
    By 99atlantic in forum C++ Programming
    Replies: 6
    Last Post: 04-21-2005, 12:41 AM
  3. Simple question about pausing program
    By Noid in forum C Programming
    Replies: 14
    Last Post: 04-02-2005, 09:46 AM
  4. simple question.
    By InvariantLoop in forum Windows Programming
    Replies: 4
    Last Post: 01-31-2005, 12:15 PM
  5. simple fgets question
    By theweirdo in forum C Programming
    Replies: 7
    Last Post: 01-27-2002, 06:58 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21