Thread: Namelist in C

  1. #1
    Registered User
    Join Date
    Jan 2017
    Posts
    1

    Namelist in C

    Hey guys
    My code needs to save a list of names from a file and sort out the ones who are appearing several times. A pointer array should be used for the strings.

    I already wrote a code but it doen't works. It crashes when I try to start is.

    Heres my code:

    Code:
    #include <stdio.h>#include <stdlib.h>
    #include <string.h>
    
    
    int main()
    {
        char *namen[500];
        char InputBuffer[255];
        int x=0, i, j, anzahl=0;
        FILE* pDatei;
        pDatei=fopen("Vornamen.txt","r");
    
    
        while(fscanf(pDatei,"%s",InputBuffer)!=EOF)
        {
            for(i=0;i<=x; i++)
            {
                if(namen[i]==InputBuffer)
                {
                    break;
                }
                else if(i==x)
                {
                    namen[x]=InputBuffer;
                    x=x+1;
                }
            }
        }
    
    
        fclose(pDatei);
    }
    So can you find an error, cause for me it should work.

    I'm programming with code::bloxx btw.

    Thankfull for very Hint

  2. #2
    Registered User
    Join Date
    Nov 2012
    Posts
    1,393
    You are using a variable before it is initialized. Look at this part:

    Code:
            for(i=0;i<=x; i++)
            {
                if(namen[i]==InputBuffer)
                {
    ...
    You try to read namen[i] before you've assigned a value, so the result is undefined (most likely it will crash). Did you forget to save the names in 'namen'?

    Other potential problems unrelated to the crash:
    - '==' is probably not what you want to do in this situation. To do string comparison, use 'strcmp'.
    - Your loop has a suspicious bound condition "i<=x". If x represents the number of elements in an array, then you probably want to use "i<x" instead. For example, suppose x is 10. Then namen[9] is probably the last valid element of your array.

    Look up how to enable warnings for your compiler in Code::Blocks. It will warn you about some problems like these when you compile.

  3. #3
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    Additional comments:

    Code:
    pDatei=fopen("Vornamen.txt","r");
    You should ensure the file has opened successfully before attempting to access it.

    Code:
    namen[x]=InputBuffer;
    To copy strings, use strcpy().

    Code:
    char *namen[500];
    This gives you an array of uninitialized pointers. If you want to store strings, you need to allocate memory to each pointer.

Popular pages Recent additions subscribe to a feed

Tags for this Thread