Qualcomm Interview Question
Software Engineer / DevelopersThis has to do with padding. Structures are usually padded with extra bytes for proper memory alignment. Thus size(struct) does not return the exact size of struct. we need to declare a struct as __(Packed)__ and then do a size of operation. There might be a better way.
yes sum an is right and it has to do with padding and it will be multiples of 4 in modern computer.... but the way you order the data members may increase or decrease the size of structure based on padding needs. but it looks like sizeof will give you the size of structure but may be the interviewer needs this padding answer to make sure you have clear understanding
#pragma pack(push) /* push current alignment to stack */
#pragma pack(1) /* set alignment to 1 byte boundary */
struct data
{
char Data1;
long Data2;
char Data3;
};
#pragma pack(pop) /* restore original alignment from stack */
So we have 2 lists A and B and we need to sum them.
Question 1. The results is again a list?
->: let's assume yes, a SUM list
Question 2. How numbers are organized? starting from the most significant ? or least significant?
-> if from most significant on, the problem is hard, so we can just reverse the list and then sum. Reversing a list is a O(n) problem and the sum is also an O(n) so the total op is O(n).
So assuming A, B lists starting from the least significant digit and the sum returns S list also from the least sig. digit the problem is:
typedef struct list_t{
int x;
struct list_t* next;
} list_t;
// add two lists and return a list
list_t* add(list_t* A, list_t *B){
int s;
list_t* least=NULL; //pointer to the sum list least impotant digit
list_t* most=NULL; //pointer to the sum list most impotant digit
list_t* tmp=NULL;
// while there are 2 digits, add them
while( A != NULL && B != NULL){
s = A->x + B->x;
// initialize sum list
tmp = malloc(sizeof(list_t));
if(least == NULL){
least = most = tmp;
}
// add either 1 or 2 digits
if(s<9){
tmp->x = s;
tmp->next = NULL;
most->next=tmp;
most=tmp;
}
else{
tmp->x = s -10;
tmp->next = malloc(sizeof(list_t));
tmp->next->x = 1;
tmp->next->next=NULL;
most->next=tmp;
most=tmp->next;
}
A=A->next;
B=B->next;
}
while( A != NULL ){
most->next=malloc(sizeof(list_t));
most->next->x = A->x;
A = A->next;
most = most->next;
}
while( B != NULL ){
most->next=malloc(sizeof(list_t));
most->next->x = A->x;
B = B->next;
most = most->next;
}
return least;
}
typedef struct {
xxxxx;
} strName;
strName strArray[2];
int size = &strArray[1] - &strArray[0];
#pragma pack(push, 1) /* set alignment to 1 byte*/
typedef struct StructSize
{
int a;
char b;
float c;
char aa;
char bb;
char cc;
char dd;
}structsize ;
#pragma pack(pop) /* set back to old alignment*/
structsize Size;
structsize *ptrSize;
ptrSize =&Size;
int Length= (char *)(ptrSize+1) - (char *)ptrSize;
/* here goes correct struct size*/
struct *ptr ;
- mailshreyas March 11, 2011int size = (char *)(ptr+1) - (char *)ptr ;