-
Notifications
You must be signed in to change notification settings - Fork 2
Description
Well, I think I am very lucky to have some simple technology questions this time.
1. Tell the difference of the flowing C statement.
(1) char * const p
(2) char const * p
(3) const char * p
Answer:
(1) const pointer p indicate the pointer can't point to other char after definition.
(2) and (3) indicates the string is a const string which means that the content is read only.
Summary: Observe that which is nearer to p, * or const. If * is nearer, than this is the latter. Otherwise, the former.
2. Tell the what's wrong with the following c program:
int countAs(char s[]) {
int length = sizeof(s) / sizeof(char);
int i, result = 0;
for(i = 0; i < length; i++) {
if(s[i] == 'A' || s[i] == 'a') {
result++;
}
}
return result;
}
Answer: sizeof(s) does not work, because you lost the length of the array in C when you passing it as an parameter. It becomes a pointer. sizeof(s) is a unchanged value.
Question: What is the value?
Answer: In 32 bits operation system, sizeof(s) is 4 while in 64 bits operation system, 8.
Question: How can you fix it?
Answer: pass one more argument indicates the length of the array.
Question: And other methods?
Answer: Using strlen() function to calculate the length of the string.
Question: What should you pay attention to when you use strlen()?
Answer: Well, you should check NULL pointers when the parameters is passed in and also there should be a '\0' char at the end of the string.
Question: And other methods?
Answer: It's unnecessary to calculate the length of the string. You can just use the '\0' char to know the end of the string when you write for loop.
Question: What other problem about the function?
Answer: The argument does not have side effect in this case, it should be made const. Also the return type int may be overflow in the case the string is too long. And the name of the function is not good in some way, make it "count_letter_a".
Interviewer: Your level of knowledge is OK. Talk about one of your project experience......