I was just playing around with some C code, trying to get the hang of it, and ended up with this:
Code:
#include <string.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
if (argc == 3) {
// get the first argument
char first[strlen(argv[1]+1)];
strncpy(first, argv[1], sizeof(first)+2);
// get the second argument
char second[strlen(argv[2]+1)];
int i;
for (i = 0; i < strlen(argv[2]) && argv[2][i] != ':'; i++)
second[i] = argv[2][i];
second[i] = '\0';
printf("0: check: %s\n", second);
char port_str[strlen(argv[2]+2)-strlen(second)];
printf("1: check: %s\n", second);
for (int c = 0; c < sizeof(port_str); c++)
port_str[c] = '\0';
printf("2: check: %s\n", second);
int j;
printf("3: check: %s\n", second);
port_str[0] = 'a';
port_str[1] = '\0';
printf("4: check: %s\n", second);
} else {
printf("wrong syntax\n");
}
}
I wanted to make a program that takes the syntax "./prog ip1 ip2
ort". The wierd this is that when I change the port_str into just an "a" the last (4th) check of the "second"-variable shows that it has changed. Here is the output:
Code:
$ gcc blahfan.c -o temp -std=c99
$ ./temp 10.11.1.11 22.222.2.22:1
0: check: 22.222.2.22
1: check: 22.222.2.22
2: check: 22.222.2.22
3: check: 22.222.2.22
4: check: a
I want "second" to stay intact. It is done, it was perfect, but then it got messed up when I changed port_str. What am I doing wrong?