網頁

2011年1月8日 星期六

Char Array

Questions about array and pointer are always popular in firmware interviews. If you can understand the following codes, you should be able to answer most the of related questions in your interview. 


Incompatible Types

 char array1[] = "abcdef";             // OK
 char array2[7];
 array2 = "abcdef";  // Error -- incompatible type
 char array3[10];
 char *p;
 p = array3;       // OK
 array3 = p;     // Error -- incompatible type

 Segmentation Faults

 char *str = "abcdef";

 *(str+1) = 'k';
 // Segmentation fault -- can't modify string constant

 char *str;
 *(str) = 'k';  
 // Segmentation fault -- char *str has no memory allocated !!!
 // because str is not initialized, its a big number

 Infinite Loop
 #include <stdio.h>
 int main()
 {
      char c = 255;  // should be changed to unsigned char
      char p[256];

      for (c = 0; c <= 255; c++) {
         // should be changed to c < 255
         printf("%d ", c);
         p[c] = c;
      }
      // assign the value of p[255] outside of the loop
  }

沒有留言:

張貼留言