E
evanevankan2
I have a question about the warning 'comparison between signed and
unsigned' I get from my code. It comes from the conditional in the
outer for loop.
I understand the warning, but I'm not sure what is the best way to
prevent it. I can just change i to a type size_t or maybe put a cast
in the conditional, but I don't know which way that is 'best'?
Any ideas? I provided the code below for some context.
And while we're at it, could you please check if the code looks good?
And last question, the signed integer in the comparison will promoted
to unsigned, right?
Could you give some examples on what could go wrong when comparing
signed and unsigned integers?
Thanks
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void *fail_malloc(size_t size)
{
void *ptr = malloc(size);
if (ptr == NULL) {
fprintf(stderr, "Memory allocation error\n");
exit(EXIT_FAILURE);
}
return ptr;
}
typedef int insertion_compare(const void *insertion_a, const void
*insertion_b);
void insertion_sort(void *data, size_t nmemb, size_t size,
insertion_compare *cmp)
{
int i, j;
char *ptr = data;
char *tmp = fail_malloc(size);
for (i = 1; i < nmemb; i++) {
memcpy(tmp, ptr + size * i, size);
for (j = i - 1; j >= 0 && cmp(ptr + size * j, tmp) > 0; j--)
{
memmove(ptr + size * (j + 1), ptr + size * j, size);
}
memcpy(ptr + size * (j + 1), tmp, size);
}
free(tmp);
}
unsigned' I get from my code. It comes from the conditional in the
outer for loop.
I understand the warning, but I'm not sure what is the best way to
prevent it. I can just change i to a type size_t or maybe put a cast
in the conditional, but I don't know which way that is 'best'?
Any ideas? I provided the code below for some context.
And while we're at it, could you please check if the code looks good?
And last question, the signed integer in the comparison will promoted
to unsigned, right?
Could you give some examples on what could go wrong when comparing
signed and unsigned integers?
Thanks
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void *fail_malloc(size_t size)
{
void *ptr = malloc(size);
if (ptr == NULL) {
fprintf(stderr, "Memory allocation error\n");
exit(EXIT_FAILURE);
}
return ptr;
}
typedef int insertion_compare(const void *insertion_a, const void
*insertion_b);
void insertion_sort(void *data, size_t nmemb, size_t size,
insertion_compare *cmp)
{
int i, j;
char *ptr = data;
char *tmp = fail_malloc(size);
for (i = 1; i < nmemb; i++) {
memcpy(tmp, ptr + size * i, size);
for (j = i - 1; j >= 0 && cmp(ptr + size * j, tmp) > 0; j--)
{
memmove(ptr + size * (j + 1), ptr + size * j, size);
}
memcpy(ptr + size * (j + 1), tmp, size);
}
free(tmp);
}