I have an array which keeps chars of a string and want to find its suffixes. If i add 7 chars in the array the total number of chars should be 7*8/2 = 28. So the suffix_array limit should be 28. When i tried to create suffix array i noticed that array has null chars ass well. So my output is wrong. What is the reason of this?
#include <stdio.h>
#include <stdlib.h>
static char *suffix;
int main()
{
char s[7] = {'c','o','n','n','e','c','t'};
suffix = (char*) malloc(sizeof (char)*28);
int j;
static int k=0;
j=k;
for(int i=0; i<28; i++) {
suffix[i] = s[j];
printf("%c ", suffix[i]);
if(j<7) {
j++;
}
else {
k++;
j=k;
}
}
return 0;
}
Output:
c o n n e c t o n n e c t n n e c t n e c t e c
>Solution :
You end up with j==7 (if (j<7) { j++; }), which is beyond the end of s.
Replace
if(j<7) {
j++;
}
else {
k++;
j=k;
}
with
j++;
if(j==7) {
k++;
j=k;
}
Tips:
-
It would be best to use
strlen(once, up front) rather than hardcoding 7 and 28. -
You don’t really use
suffix. But if you wanted to build a string insuffix, make sure to allocate one more char for the trailing NUL and to add the trailing NUL! -
const char *s = "connect";would do fine.