开发者

array subscript operator in for loop counter

I am learning C. In the following code why does replacing "*ptr_str" with "ptr_str[i]" in the for loop truncate?

/* 13L01.c: Initiali开发者_开发问答zing strings */
#include <stdio.h>
main()
{
 char str1[] = {'A', ' ',
 's', 't', 'r', 'i', 'n', 'g', ' ',
 'c', 'o', 'n', 's', 't', 'a', 'n', 't', '\0'};
  char str2[] = "Another string constant";
  char *ptr_str;
  int i;

  /* print out str2 */
  for (i=0; str1[i]; i++)
      printf("%c", str1[i]);
      printf("\n");
  /* print out str2 */
  for (i=0; str2[i]; i++)
      printf("%c", str2[i]);
      printf("\n");
   /* assign a string to a pointer */
   ptr_str = "Assign a strings to a pointer.";
   for (i=0; *ptr_str; i++)
       printf("%c", *ptr_str++);
   return 0;

}


   // A, ok
   while (*ptr_str)
       printf("%c", *ptr_str++);

   // B, also ok
   for (i=0; ptr_str[i]; i++)
       printf("%c", ptr_str[i]);

   // C, works but ugly
   for (i=0; *ptr_str; i++)
       printf("%c", *ptr_str++);

C is your form, it is flawed because i is doing nothing here, so A is an improved version. If you want to use i, do it like B. If you use both i and ptr_str, and increment both of them in the loop, nothing good will happen. Increment one or the other.


Because you're advancing ptr_str and then treating it as an array and testing if it's pointing to NULL on the i'th member. You're basically testing if ptr_str[i+i] is NULL instead of ptr_str[i].


Your question is a bit unclear, but I think I've got it:

In the following code why does replacing "*ptr_str" with "ptr_str[i]" in the for loop truncate?

I think you mean changing this:

for (i=0; *ptr_str; i++)
    printf("%c", *ptr_str++);
return 0;

to this:

for (i=0; ptr_str[i]; i++)
    printf("%c", *ptr_str++);
return 0;

The second one truncates because you're advancing i and ptr_str, so the modified starting position of ptr_str plus the modified starting position of i ends up cutting you off too soon (or worse, having an odd number of characters and overflowing into data that isn't yours). The second example that truncates is equivalent to:

for (i=0; ptr_str[i * 2]; i++)
    printf("%c", ptr_str[i]);
return 0;

Now do you see why it truncates?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜