Stuck on this code. Can someone please help? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Stuck on this code. Can someone please help?

Hello! I was writing a code to convert US date(mm/dd/yyyy) to EU date and I got stuck. the problem is that the loop: while(date[i] != '\0'){ addchar(date[i],year); i++; } changes the string date, although it's not supposed to. Here is a part of my code. Could you take a look? Thank you in advance ;) ----------------------------------- //language: C #include <stdio.h> #include <stdlib.h> #include <string.h> int index_of(char ch, char arr[]){ int i = 0; while(i <= strlen(arr)){ if(arr[i] == ch) return i; i++; } return -1; } int last_index_of(char ch, char arr[]){ long int i= strlen(arr)-1; while(i >= 0){ if(arr[i] == ch) return i; i--; } return -1; } void addchar(char ch,char str[]){//adds a character to the string char arr[1]; arr[0]=ch; strncat(str,arr,1); } //I've tested the functions above and they seem to be working correctly. void convert(){ char date[100];//date = mm/dd/yyyy scanf("%s", date);//enter a date printf("date = %s\n", date); //erverything is fine char year[1]; int i = last_index_of('/',date)+1; printf("date = %s\n",date); //erverything is fine while(date[i] != '\0'){ addchar(date[i],year); i++; } printf("year = %s\n", year); //still everything is fine printf("date = %s\n", date); //problem } int main() { convert(); return 0; }

28th Mar 2020, 4:18 PM
H2727
H2727 - avatar
2 Answers
+ 3
Here is the problem: char year[1]; It is writing past the end of year[] into the next variable on the stack, which is date[]. You need to declare at least 5 characters in year[] to store a 4-digit year plus null terminator. Also you should initialize year[0] = '\0'; to ensure strncat() starts in the right place.
28th Mar 2020, 6:47 PM
Brian
Brian - avatar
0
Thanks!
28th Mar 2020, 8:33 PM
H2727
H2727 - avatar