Page 1 of 1

Arrays in C

Posted: Fri Jan 23, 2004 9:42 pm
by nigma
Hey, say I have the following C code:

Code: Select all

char carrayї] = "test";
char letter = carrayї10];
What would the value of 'letter' then be? NULL?

Posted: Sat Jan 24, 2004 3:19 am
by microthick
No, it wouldn't be null.

It would exit due to an out of bounds error.

Posted: Sat Jan 24, 2004 10:24 am
by nigma
I recently discussed this with a friend and heres what he said:
It would be a pointer overflow.

carray[10] is the same as
char *foo = carray;
bar = foo + 10;

carray[10] would be equal to *bar;
After reading this I actually compiled the following code:

Code: Select all

#include <stdio.h>

int main (void)
&#123;
  char letters&#1111;] = "test";
  char letter = letters&#1111;10];
  printf("%c", letter);

  return 0;
&#125;
When executed it prints some wierd ascii symbol.

But then out of curiousity I tried the following:

Code: Select all

#include <stdio.h>

int main (void)
&#123;
  char letters&#1111;] = "test";
  int idx =0;
  while (letters&#1111;idx] != NULL)
  &#123;
    idx++;
  &#125;
  printf("%d", idx);

  return 0;
&#125;
When run, the latter program will print 4. Can you tell me why letters[4] would test true when asked if it is equal to NULL?

Posted: Sat Jan 24, 2004 1:11 pm
by microthick
It may have originally printed that weird ascii character because it printed whatever was in memory at that location.

In C++, if you were to create a string called letters with a value "test", then letters[4] would be the end of string character \0.

Since this is a char array, letter[4] might not be \0 and might actually just grab whatevers in memory right after the "t" in test. And it could be null.

That's what I think anyhow.

It's like going:

char c;
cout << c;

Never sure what c would output.

Posted: Sat Jan 24, 2004 4:25 pm
by nigma
Alright. Could I PM you another question I have regarding pointers and function arguments in C?

Thanks a bunch for the help. Kudos on your sites layout, it's pretty sweet.

Posted: Sat Jan 24, 2004 8:43 pm
by microthick
Sure, go ahead.