Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why null chars added in array?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 in suffix, make sure to allocate one more char for the trailing NUL and to add the trailing NUL!

  • const char *s = "connect"; would do fine.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading