I am fairly new to C and am just overcoming my fear of pointers and segmentation faults. C is a strange language to me because I come from more object oriented languages like JavaScript and Java.
When I code in C, everything feels all "one-liney" to me. I'm used to things, for example in Java, being neatly spread out, everything with it's own clean section in the code.
When I see C(ha) that I write, everything is all in one place and nothing has it's own area.
Here is an example piece of code that I recently wrote. It takes all the command line arguments and puts them all into one string with each word separated by a space (dismiss any and all spelling errors):
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if(argc == 1) { // if there are too few arguments
printf("ERROR: Expected atleast 1 argument\n");
return 0;
}
int size = 0;
while(argv[size]) { // gets the amount of arguments besides the first argument
size++;
}
size--;
if(size == 1) { // if there is only 1 word
printf("%s\n", argv[1]);
return 0;
}
int i;
int v = strlen(argv[1]) + strlen(argv[2]); // for allocating memroy
char *str = (char *)malloc(v);
strcat(str, argv[1]); // putting the string together
strcat(str, " ");
strcat(str, argv[2]);
strcat(str, " ");
for(i = 3; i <= size; i++) {
str = (char *)realloc(str, (v + strlen(argv[i]))); // reallocates enough memory
strcat(str, argv[i]);
strcat(str, " ");
}
printf("%s\n", str);
return 0;
}
One thing that I read somewhere about C involving convention is that C should be broken up into smaller bits of code (functions?). Is this true, and what else should I work on?