char** names=(char**)malloc(count*sizeof(char*));
//while loop
names[count]=(char*)malloc(size+1);//why malloc again?
So char** names=(char**)malloc(count*sizeof(char*)); creates a pointer to a location hosting 4 times count bytes and then stores pointer location to names?
Then in the while loop, size+1 bytes long memory is allocated and its address is given to names[count], which refers to the location pointed to by names? So here the memory created from the first malloc stores the location of memory created by the second malloc? And is the size of memory pointer 4 bytes, so that I can access each names[count] by moving to the next 4 bytes starting from the start of the memory location?
If my thinking is correct, are these correct NASM implementations of these two lines of c code:
;char** names=(char**)malloc(count*sizeof(char*));
mov eax, dword count
;lea ebx, [eax*4]
imul ebx, eax, 4
push ebx
call _malloc
mov names, eax
add esp, 4
;names[count]=(char*)malloc(size+1);
mov ebx, size
inc ebx
push ebx
call _malloc
add esp,4
mov ebx, names
mov ecx, dword count
mov [ebx+ecx*4], eax
Fyi, also, these two lines of code are part of the following c code to extract names from a file and sort them:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char path[]="names.txt";
char szName[50];
int count=0;
int size=0;
int x=0;
int y=0;
char* temp=0;
int pos=0;
FILE* file=fopen(path,"rt");
if (file){
while (!feof(file)){
fscanf(file,"%50s",szName);
count++;
}
}
else{
printf("Error opening file\n");
return 1;
}
printf ("Count: %d\n",count);
char** names=(char**)malloc(count*sizeof(char*));
rewind(file);
count=0;
while (!feof(file)){
fscanf(file,"%50s",szName);
size=strlen(szName);
names[count]=(char*)malloc(size+1);
strcpy(names[count],szName);
count++;
}
printf("Original file\n");
for (x=0;x<count;x++){
printf("Name %d:\t%s\n",x+1,names[x]);
}
for (x=0;x<count;x++){
temp=names[x];
pos=x;
for (y=x;y<count;y++){
if (strcmp(temp,names[y])>0){
temp=names[y];
pos=y;
}
}
temp=names[x];
names[x]=names[pos];
names[pos]=temp;
}
printf("Sorted names\n");
for (x=0;x<count;x++){
printf("Name %d:\t%s\n",x+1,names[x]);
}
system("PAUSE");
return 0;
}