Harout Tatarian Harout Tatarian - 3 months ago 67
C Question

C program that returns the initials of a name (CS50)

Here's my

main


char* name = GetString();
if(name != NULL)
{
for(int i = 0, j = strlen(name); i < j; i++)
{
if(!isalpha(name[i-1]) && isalpha(name[i]))
printf("%c", toupper(name[i]));
}
printf("\n");
}


The program works pretty good; it passed all the (check50) tests.

But I'm worried about a possible bug and that is when
i = 0
, could the value stored in
name[-1]
be an alpha character?

Note: the
GetString()
function returns a string entered by the user.

Answer

Actually in C, the [] operator can be replaced with *().

  • a[n] is equal to *(a+n);

So, in your case, when i = 0, you're accessing *(a - 1) location while your string begins from a to a + length. So, this would result in unknown behavior.

+----+----+----+----+
| f  |  o | o  | \0 |
+----+----+----+----+
  ^              ^
  |              |
  a            a + 3