I have 2 questions.
First question is that, I'm trying to find the frequency of the sentence and put them into another array. However, the output of the new frequency nfreq
is different from what is appended in for loop.
void append(char* s, char c)
{
int len = strlen(s);
s[len] = c;
s[len+1] = '\0';
}
int main()
{
char str[] = "test sentence";
char nstr[] = "";
int freq[256] = {};
int nfreq[256] = {};
for(int i = 0; str[i] != '\0'; i++)
{
freq[str[i]]++;
}
printf("\nCharacter Frequency\n");
int j = 0;
for(int i = 0; i < sizeof(freq) / sizeof(int); i++)
{
if(freq[i] != 0)
{
printf("%5c%10d\n", i, freq[i]);
char c = i;
append(nstr, c);
int f = freq[i];
nfreq[j] = f;
printf("Num in nfreq[%d] is %d\n", j, nfreq[j]);
j++;
}
}
for(int i = 0; i < strlen(nstr); i++)
{
printf("%d ", nfreq[i]);
}
printf("\n");
printf("size of nfreq : %lu\n", sizeof(nfreq) / sizeof(nfreq[0]));
printf("size of str : %lu\n", strlen(str));
printf("size of nstr : %lu\n", strlen(nstr));
printf("nstr is : %s\n", nstr);
return 0;
}
The frequency of each letter is
Character Frequency
1
c 1
e 4
n 2
s 2
t 3
and nfreq
should have those {1, 1, 4, 2, 2, 3}
in its array with the code above and it even
says Num in nfreq[0] is 1
and etc in the loop, but when I try to check what's in nfreq
outside the loop, it outputs {116, 1, 4, 2, 2, 3}
this instead. What is this 116
and it should be 1
for the frequency of ' '
.
Also the second question is that, if I were not to declare the size of an int array, int nfreq[] = {}
like so in the beginning, does the size of this array, after appending int with for loop, changes dynamically? Or does it stay 0?
I tried fixing it by not declaring the size (which I don't think it matters) of nfreq
array.
Thanks in advance for your help :)
Edit : Sorry I forgot to add append function.