I am trying to write a function which compares first two digits of a number, and since itoa is not available, I am using sprintf as found by googling previously to first convert number to string and then compare each digit. For some strange reason, I am getting seg faults when I run this. I tried same thing but using actual strings like strncmp("100", "101", 2) and it gives no issues. The problem is because of two sprintf statements which somehow messes up str2. I cannot find anywhere why this is happening and what I can do to fix it. Spent 2 hours on this before posting here. Would appreciate some help, if possible
int exists;
int id1 = 100;
int id2 = 101;
char str1[12];
char str2[12];
sprintf(str1, "%d", id1);
sprintf(str2, "%d", id2);
exists = strncmp(str1,str2,2);
printf("Res is %d\n", exists);
Edit: I've tried printf both str1 and str2 and they show 100 and 101 respectively. I also tried iterating thru char arrays but got seg fault again. I actually was able to run it successfully when I created a test file and it all ran so I am totally lost
Edit #2: To add context, this program has multiple files in it and some libraries are included in other files. Everything is properly surrounded by #ifndef. Question is can the order of file compilation produce this issue?
Not 100% sure that I found the correct solution but I believe my issue was linked to malformed makefile. Specifically I previously had this:
And after I changed CC to CC = gcc, it started working. I had to strip my main.c before though and proceed slowly as noted above by simonc and Jonathan Leffler.