Jord Jord - 4 months ago 8
C Question

Why does this printf statement, or lack there of, alter the effect of the for loop?

First section of code:

#include <stdio.h>
#include <cs50.h>
#include <string.h>

int main(void)
{
string name = GetString();
int n = strlen(name);
int j = 0;
int c = 0;
char initials[j];
char input[c];
char space[] = {' '};

for (int i = 0, c = 0; i < n; i++, c++)
{
input[c] = name[i];

printf("%c, %c\n", name[i], input[c]);
}


Problem area:

printf("%d\n", n);
for (int i = 0, c = 0; i < n; i++, c++)
{
if (input[c] != space[0])
{
initials[j] = input[c];
j++;
break;
}
printf("loop test\n");
}

j = 0;

printf("%c\n", initials[j]);
}


If my input is:

hello


Then my output is what I want (loop test == number of spaces before input):

loop test
loop test
loop test
loop test
loop test
h


Unless, I remove:

printf("%d\n", n);


Then if my input starts with >= 4 spaces, my output is:

loop test
loop test
loop test
loop test
// blank line
// blank line


the two comments are actual blank lines in the output

*Sorry for some of the erroneous printf statements, I was trying to identify the bug.

Answer

One major problem is here:

int c = 0;
 ...
char input[c];

input[] is made a zero length array. Then the code merrily writes beyond the end of it which amounts to random writing on other parts of the stack frame.

The fix is to properly size the array before writing into it.

There is also

int j = 0;
 ...
char initials[j];