Still learning, this is a segment of code I'm working on and I'm trying to remove an element(s) from a pointer/pointer-pointer. The problem is near the end of the code.
int total, tempX = 0;
printf("Input total people:\n");fflush(stdout);
scanf("%d",&total);
printf("You entered: %i\n", total);
char **nAmer = (char**) malloc(total * sizeof(char*)); //pointer pointer for username
for (tempX=0; tempX<total; tempX++){
nAmer[tempX] = malloc(21);
}
double *nUmer = (double*) malloc(total* sizeof(double)); //pointer for usernumber
printf("input their name and number:\n");fflush(stdout);
for (tempX = 0; tempX<total; tempX++){
scanf("%20s %lf", nAmer[tempX], &nUmer[tempX]);
}
printf("Let me read that back:\n");
for (tempX = 0; tempX<total; tempX++){
printf("Name: %s Number: %lf\n", nAmer[tempX], nUmer[tempX]);
}
char *searcher = (char*) malloc(21 * sizeof(char*)); //temporary string made by the user to compare names
printf("Enter name to remove user(s):\n");fflush(stdout);
scanf("%20s",searcher);
for (tempX = 0; tempX < total; tempX++){
if (strcmp(searcher,nAmer[tempX])==0){ //what is better to replace this section?
free(nAmer[tempX]); //I can assume this wont work well
free(nUmer[tempX]); //I know this is a problem
}
}
printf("Let me read that back with removed user(s):\n");fflush(stdout);
for (tempX = 0; tempX<total; tempX++){
printf("Name: %s Number: %lf\n", nAmer[tempX], nUmer[tempX]);
}
I know free (nAmer[tempX]);
works but doesn't allow for the read back after its removal. What would fix this?
You shouldn't
free(nUmer[tempX]);
because this isn't a pointer.When you free one of the name pointers, you can set it to
NULL
. Then the loop that prints the array that can skip it.You have another mistake:
This should just be
* sizeof(char)
(or you can just leave this out, sincesizeof(char)
is defined to be1
).Luckily this allocates more memory than needed, not less.