Pedro Viana
Pedro Viana

Reputation: 9

Strange Characters on terminal

Could someone explain me, why I'm getting these strange characters on output?

I got this code:

#include <stdio.h>
#include <string.h>

int main(int argc, char* argv[]){
    if(argc!=2){
        printf("Incorrect number of arguments\n");
        return -1;
    }
    int lenServer=0;
    int i=0;
    while(argv[1][i]!=':'){
        lenServer++;
        i++;
    }

    char server[lenServer];
    memcpy(server,argv[1],lenServer);

    printf("%s\n",server);
    return 1;

}

I got this on terminal:

pedro@pedro-VirtualBox:~/Desktop/SDMEU$ gcc table_client.c -o table-client
pedro@pedro-VirtualBox:~/Desktop/SDMEU$ ./table-client ola:eu
ola N
pedro@pedro-VirtualBox:~/Desktop/SDMEU$ 

Shouldn't I just get ola?

Upvotes: 0

Views: 100

Answers (1)

BLUEPIXY
BLUEPIXY

Reputation: 40145

put a NUL('\0') to the end of the string.

char server[lenServer+1];
memcpy(server,argv[1],lenServer);
server[lenServer]=0;

Upvotes: 2

Related Questions