Thread: Sorting algorithm with dynamic memory allocation help

  1. #1
    Registered User
    Join Date
    Nov 2013
    Posts
    11

    Sorting algorithm with dynamic memory allocation help

    Hello I am fairly new to dynamic memory allocation and I keep getting a segmentation fault in this code of mine. Could anyone tell me where my error is or could be?

    This is what the method should do:
    void sortStringsByReversePoints(char **myWords): This function sorts the char* values (i.e. strings) of myWords in descending order of point value by calling getWordPoints as a helper function and comparing adjacent words. This simple (but inefficient) sorting algorithm starts at the beginning of myWords array and sweeps to the end comparing adjacent values and swapping if they are out of order. After N (length of the array) sweeps the array is fully sorted. Note that efficiency can be improved by a factor of 2 by shortening each successive sweep by one, since the first sweep will have guaranteed the minimum point value word is the last element of the array, the next sweep guarantees the last two elements are correct, and so on....Additionally, if a given sweep results in zero swaps then the array is sorted and you can return immediately.
    Attached Images Attached Images Sorting algorithm with dynamic memory allocation help-screen-shot-2013-11-17-7-25-06-pm-jpg 

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Instead of posting an image, post your code in [code][/code] bbcode tags.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Nov 2013
    Posts
    31
    Sizeof(words) returns the size of the pointer not the actual length of the array, I believe. You should pass in the length of your arrays into the function parameters.

  4. #4
    Registered User
    Join Date
    Nov 2013
    Posts
    11
    Code:
    #include<stdio.h>#include<stdlib.h>
    #include<string.h>
    
    
    #define BUFFER_SIZE 256
    // returns an array of strings (char[])
    // last entry is a NULL pointer
    char **getListOfWords(char filename[])
    {
        FILE *fp;
        char buffer[BUFFER_SIZE];
        char **words;
        int M, nLines = 0, nAlloc = 1;
        
        // initialize array of char pointers (for strings)
        words = (char **)malloc(nAlloc*sizeof(char *));
        
        fp = fopen(filename, "r");
        while(!feof(fp))
        {
            fscanf(fp, "%s", buffer);
            M = strlen(buffer);
            words[nLines] = (char *)malloc((M+1)*sizeof(char));
            strcpy(words[nLines], buffer);
            
            nLines++;
            if(nLines >= nAlloc)
            {
                nAlloc *= 2;
                words = (char **)realloc(words, nAlloc*sizeof(char *));
            }
        }
        words[nLines] = NULL;
        words = (char **)realloc(words, (nLines + 1)*sizeof(char *));
           
        fclose(fp);
        
        return words;
    }
    
    
    void freeWords(char **words)
    {
        int i;
        
        for(i=0; words[i] != NULL; i++)
        {
            free(words[i]);
        }
        free(words);
    }
    
    
    int canWeMakeIt(char word[], char letters[])
    {
    	int n = strlen(letters) + 1;
    	int i;
    	char temp[n];
    	strcpy(temp,letters);
    	int found;
    	for(i=0;i<strlen(word);i=i+1) //for each char in word, search temp
    	{
    			found = 0;
    			for(n=0;n<strlen(temp);n=n+1)
    			{
    				if(word[i] == temp[n])
    				{
    					temp[n] = '-';
    					found = 1;
    					break;
    				}
    			}
    			
    			// if i not in temp
    			if(found==0)
    			{
    				return 0;
    			}
    	}
    	return 1;
    	
    }
    
    
    // the code below does not work: Tue Nov 12, 2:16 PM
    char **getScrabbleWords(char **allWords, char letters[])
    {
    	int nAlloc;
    	int i;
    	nAlloc = 1;
    	char ** myWords = (char **) malloc(nAlloc*sizeof(char *));
    	for(i=0;i<=(sizeof(allWords));i++)
    	{
    		if(canWeMakeIt(allWords[i],letters)==1) //it can be made
    		{
    			myWords[nAlloc-1] = allWords[i];
    			nAlloc = nAlloc +1;
    			myWords = (char **) realloc(myWords,(nAlloc*sizeof(char *)));
    		}
    	}
    	myWords[nAlloc-1] = NULL;
    	return myWords;
    }
    
    
    int getWordPoints(char word[])
    {
        int letterPoints[] = {1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10,1, 1, 1, 1, 4, 4, 8, 4, 10};
        int position;
        int points;
        int i;
        for(i=0;i<=(sizeof(word));i=i+1)
        {
    		////'z' - letter
    		position = word[i] - 'a';
    		points = points + letterPoints[position];
    	}
    	return points;
    }
    
    
    void sortStringsByReversePoints(char **myWords)
    {
        int i, j, length;
        char *swap = (char *)malloc(1*sizeof(char *));
        for(i = 0; i <sizeof(myWords); i++)
        {
            for(j = 1; j < sizeof(myWords); j++)
            {
                if (strlen(myWords[i]>= strlen(myWords[j])))
                          length = strlen(myWords[i]);
                else
                          length = myWords[i];
                swap = (char *) realloc(myWords,(length*sizeof(char *)));
                if(getWordPoints(myWords[i])< getWordPoints(myWords[j]))
                {
                    *swap = myWords[i];
                    myWords[i] = myWords[j];
                    myWords[j] = *swap;
                }
            }
        }
    }
    
    
    int main(int argc, char *argv[])
    {
        char **allWords, **myWords;
        int i, j, M;
        
        allWords = getListOfWords("wordlist.txt");
        myWords = getScrabbleWords(allWords, argv[1]);
        /*sortStringsByReversePoints(myWords);
        
        
        for(i=0; myWords[i] != NULL; i++)
        {
            printf("%d %s\n", getWordPoints(myWords[i]), myWords[i]);
        }
        
        
        for(i=0; allWords[i] != NULL; i++)
        {
            printf("Word %d: %s\n", i, allWords[i]);
        }
        
        
        
        
         //Test cases for canWeMakeIt - un-comment when testing - remove before submitting
        printf("canWeMakeIt(\"abba\", \"ab\") = %d\n", canWeMakeIt("abba", "ab"));
        printf("canWeMakeIt(\"ab\", \"aba\") = %d\n", canWeMakeIt("ab", "aba"));
        */
    
    
    
    
        freeWords(allWords);
        free(myWords);
        
        return 0;
    }

  5. #5
    Registered User
    Join Date
    Nov 2013
    Posts
    11
    Would that work? Does strlen work in the same way as a one dimensional array when you use it in a two dimensional array?

  6. #6
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    A row in a two dimensional array, is a one dimension array.

    So

    words[10][30] //longest REAL word in the English language is 29 letters, so 30 to cover the 0 end of string marker char.

    words[i] is a one dimension array, that can be used for string comparisons using strcmp(words[i],tempWord), or for printing("%s\n",words[i]); etc.

    I hate to ask, but I must: What the hell are you trying to do with this program?
    Last edited by Adak; 11-18-2013 at 05:34 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Dynamic Memory Allocation
    By slash.hack in forum C Programming
    Replies: 9
    Last Post: 09-30-2011, 04:31 AM
  2. Dynamic Memory Allocation
    By schifers in forum C Programming
    Replies: 12
    Last Post: 05-14-2008, 01:49 PM
  3. Replies: 16
    Last Post: 01-01-2008, 04:07 PM
  4. dynamic memory allocation w/o new
    By bd43274 in forum C++ Programming
    Replies: 11
    Last Post: 02-15-2006, 02:12 AM
  5. dynamic memory allocation - Please help
    By Space_Cowboy in forum C++ Programming
    Replies: 5
    Last Post: 11-13-2002, 05:20 PM

Tags for this Thread