Your primary issue is that
A=(int*)malloc(sizeof(int)*n);
allocates space for n
objects with the size of int
, and you later refer to this memory through a pointer to objects of size long int
. If these types are not the same size, you run the risk of reading and writing with incorrect memory sizes.
A good practice is to use the identifier with the sizeof
operator
array = malloc(sizeof *array * length);
so that if the type of array
changes, the expression here does not need to.
The "%d"
conversion specifier for scanf
expects an int
. For long int
, you'll need "%ld"
. For unsigned int
, you'll need "%u"
.
Additionally, c
is never initialized, and thus
if(x<c)
will invoke undefined behavior by reading the value of it.
Other issues:
There are two signatures for main
that you should use:
int main(void)
, or
int main(int argc, char **argv)
(or equivalent).
You should not cast the return of malloc
.
scanf
can fail, and you should be prepared to handle these events.
The proper type for storing sizes of objects is size_t
. This should be used when iterating on array indices.
Using signed types for sizes and iteration counts can lead to strange edge cases.
Coding style is subjective, but I'm willing to bet most would find the style of this code to be very hard to read. Be smart, not clever - try to use more meaningful variable names, use clear and consistent indentation, and don't be so afraid of the spacebar.
A more complete example:
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
void die(const char *msg) {
fprintf(stderr, "%s\n", msg);
exit(EXIT_FAILURE);
}
unsigned int andxoror(long int a, long int b) {
return (a & b) ^ (a | b);
}
int main(void) {
unsigned int lowest, calculation, times;
long int *array;
size_t length;
printf("Input number of repetitions: ");
if (scanf("%u", ×) != 1)
die("Invalid repetition input.");
while (times--) {
printf("Input length of array: ");
if (scanf("%zu", &length) != 1)
die("Invalid length input.");
if ((array = malloc(sizeof *array * length)) == NULL)
die("Could not allocate memory.");
for (size_t i = 0; i < length; i++) {
printf("Input array member %ld of %ld: ", i + 1, length);
if (scanf("%ld", array + i) != 1) {
free(array);
die("Invalid array member input.");
}
}
lowest = UINT_MAX;
for (size_t i = 0; i < length - 1; i++)
for (size_t j = 1; j < length; j++)
if (i != j && (calculation = andxoror(array[i], array[j])) < lowest)
lowest = calculation;
printf("Final calculation: %u\n", lowest);
free(array);
}
}