Hi, I'm in trouble with strings and pointers. It's a long message, but if anyone could read and say something, I'd be pleased.
1)
Code:
main() {
char *a;
printf("%d", strlen(a));
}
This code prints "0". But if I declare another char b[10] next to it, it begins printing 11. In this case, if I declare a as char *a="", again it prints "0". I used Codeblocs with Mingw here. And if I move the char line with or without b out of main(), it crashes in the beginning of runtime.
It acts different in DevC++. If "char *a;" is in main, it simply crashes in runtime. If I add b[10], it prints "0". If I move the char line with or without b out of main(), it still crashes. The problem is solved if a is initialized as ="".
Why do these compilers act different? And what causes this problem? I think it's because of the lack of initialization; but I saw somebody saying "You don't need". Which is true, and can i initialize a string or a "pointer to string" as a=""? Does it cost 0 byte?
2) A second problem, with dynamic memory allocation. I want to get some text from the user, and assign it to an array of characters. It has to be done dynamically. I want to get all the characters one by one, until it is '\n', and allocate place for one more char every time and assign. Here's a code I tried to do this, but I think it's far away from doing the job.
Code:
main() {
char *a = "\0", *b = "\0";
char c;
int i = 0;
while ((c = getchar()) != '\n') {
b = (char *)malloc((strlen(a) + 1) * sizeof(char));
strcpy(b, a);
b[strlen(a)] = c;
b[strlen(b)] = '\0';
free(a);
a = (char *)malloc(strlen(b) * sizeof(char));
strcpy(a, b);
free(b);
}
a[strlen(a)] = '\0';
printf("%s, %d, %d", a, strlen(a), strlen(b));
}