Arrays in C

XML, Perl, Python, and other languages can be discussed here, even if it isn't PHP (We might forgive you).

Moderator: General Moderators

Post Reply
User avatar
nigma
DevNet Resident
Posts: 1094
Joined: Sat Jan 25, 2003 1:49 am

Arrays in C

Post 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?
microthick
Forum Regular
Posts: 543
Joined: Wed Sep 24, 2003 2:15 pm
Location: Vancouver, BC

Post by microthick »

No, it wouldn't be null.

It would exit due to an out of bounds error.
User avatar
nigma
DevNet Resident
Posts: 1094
Joined: Sat Jan 25, 2003 1:49 am

Post 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?
microthick
Forum Regular
Posts: 543
Joined: Wed Sep 24, 2003 2:15 pm
Location: Vancouver, BC

Post 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.
User avatar
nigma
DevNet Resident
Posts: 1094
Joined: Sat Jan 25, 2003 1:49 am

Post 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.
microthick
Forum Regular
Posts: 543
Joined: Wed Sep 24, 2003 2:15 pm
Location: Vancouver, BC

Post by microthick »

Sure, go ahead.
Post Reply