Reputation: 222
I am making a function in C which removes any duplicates form a string.
If I run this code and provide the index
in main()
function it works.
char *clean(char *list, int index) {
int val = 0;
char temp_list[index];
for (int i = 0; i < index; i++) {
if (list[i] != list[i + 1]) {
temp_list[val] = list[i];
val += 1;
}
}
for (int y = 0; y < val; y++) {
list[y] = temp_list[y];
}
return list;
}
But if I run this code it doesn't seem to work.
char *clean(char *list) {
int index = strlen(list);
int val = 0;
char temp_list[index];
for (int i = 0; i < index; i++) {
if (list[i] != list[i + 1]) {
temp_list[val] = list[i];
val += 1;
}
}
for (int y = 0; y < val; y++) {
list[y] = temp_list[y];
}
return list;
}
In the second code the index is always zero.
Can anyone explain me why is strlen()
function not working.
Upvotes: 0
Views: 67
Reputation: 144685
The problem is not where you think: you do not set the null terminator when reducing the length of the string, so the modified list
still has the trailing bytes in place and reachable.
Here is a modified version without a temporary array:
#include <stddef.h>
char *clean(char *s) {
size_t i, j;
for (i = j = 0; s[i] != '\0'; i++) {
if (s[i] != s[i + 1]) {
s[j++] = s[i];
}
}
s[j] = '\0';
return s;
}
Upvotes: 1