Thread: GetComputerName

  1. #1
    Unregistered
    Guest

    GetComputerName

    Why isn't this working.

    #incude <stdio.h>
    #include <windows.h>

    int main() {
    int len = 255;
    char cName[255];

    GetComputerName(cName, &len);

    return 0;
    }


    WHy wont simple api compile ?

  2. #2
    Unregistered
    Guest
    What kind of project did you start?

    Windows apps usually have a WinMain not main.

    Also you have incorrectly allocated the buffer length. Forgot the '\0' will be added after the name.

  3. #3
    Unregistered
    Guest
    Okay Here is whats up.

    Im using a Windows Console program. (not a problem)

    Here is my code.



    #include <windows.h>
    #include <stdio.h>


    int main() {

    char *cName;
    int len = 55;
    if(GetComputerName(cName, &len)) {
    printf("Computer Name: %s",cName);
    } else {
    printf("Error");
    exit(1);
    }

    return 0;
    }


    Here is the error.



    --------------------Configuration: test - Win32 Debug--------------------
    Compiling...
    test.cpp
    c:\crap\test\test.cpp(13) : error C2664: 'GetComputerNameA' : cannot convert parameter 2 from 'int *' to 'unsigned long *'
    Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
    Error executing cl.exe.



    NOTE: I have also tried unsigned long len;
    Did not work either.
    Thanks
    test.obj - 1 error(s), 0 warning(s)

  4. #4
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,793
    Code:
    #include <windows.h>
    #include <stdio.h>
    
    
    int main() {
    
    char cName[MAX_COMPUTERNAME_LENGTH + 1]; //need to allocate space
    DWORD len = 55;//needs DWORD
    if(GetComputerName(cName, &len) != 0) {
    printf("Computer Name: %s",cName);
    }
    else {
    
    printf("Error");
    exit(1);
    }
    
    return 0;
    }
    2 Errors... 1 east to solve, 1 nastier runtime error

    1. As per compiler warning you need to send the address of an unsigned long (DWORD) instead of an int.....

    2. You sent a pointer that did not point to enough space to hold the returned computer name.

Popular pages Recent additions subscribe to a feed