I’m trying to copy data from an array of character that send from main to another one in my local function and I always see garbage characters even though I’ve add '\0' at the end of the string.
Here is my partial of the code.
for (int i = 0; i < strlen(main) ; i++){
if (main[i] != ';'){
local[i] = main[i]; // Copy the characters until `;` isn't found
} else {
local[i] = '\0' ; // If `;` found, null terminate the copied destination.
break;
}
}
so basically the data that being send from main for example like this
look;can;you;see;me
My Local-----> 'look??y??>c?Lw?T?w??>c?2+a?'
Actual data in main---> 'look'
As you can see from the above example I’m trying to get only the first word and I always get garbage I don’t know why?
EDIT:
This is the almost the whole function which 100% sure that is causing me the problem.
void myFunction(char main[ ]){
for (int i = 0; i < strlen(main) ; i++){
if (main[i] != ';'){
local[i] = main[i]; // Copy the characters until `;` isn't found
} else {
local[i] = '\0' ; // If `;` found, null terminate the copied destination.
break;
}
}
if(main[i] != '\0'){
int col = 0, row = 0;
do {
if(main[i] == ';' || main[i] == '\0') {
sending[row++][col] = '\0';
col = 0;
} else {
sending[row][col++] = main[i];
}
} while(main[i++] != '\0');
}
}
You are forgetting to take care of zero terminating the string if the ; is not found. A simple fix is tweaking your for loop so it also sees the \0 in main: