I've stumbled upon an interesting problem while preparing for my exam, and I'm unsure as to whether I've solved it or not. I will provide the text of the problem, as well as my code:
void charAlloc(){
char *arrPtr;
arrPtr = malloc(sizeof(char)*100);
int i;
for (i=0; i<101; i ){
if (*(arrPtr i) % 5 == 0){
*(arrPtr i) = 'a';
}
if (*(arrPtr i) % 3 && *(arrPtr i) % 7 != 0 && *(arrPtr i) / 2 != 0){
*(arrPtr i) = 'b';
}
else{
*(arrPtr i) = 'c';
}
}
free(arrPtr);
}
Since it's a void function there isn't really a way to check if it's doing what it's supposed to in this case, so I thought I'd ask here. I do sometimes struggle with pointers so it's quite possible I maybe messed up something there. There's no errors or warnings in the compiler.
CodePudding user response:
Question has been answered in the comments. Firstly, instead of going through the loop for 101
times, it should iterate 100
times: for(i=0; i<100; i )
.
The next mistake was in the if
branches within the loop. What *(arrPtr i)
does is it selects the value stored at that address.
This is not the value of the index, but rather a garbage value appointed to the heap.
What I should've done instead is checked for the values of i
, and assign the values given in the problem to *(arrPtr i)
.
There was another mistake pointed out within the if
branches. In the second if
conditional, for assigning value 'b' to certain indexes, the testing statements are incorrect. They stated:
if (*(arrPtr i) % 3 && *(arrPtr i) % 7 != 0 && *(arrPtr i) / 2 != 0)
Which is incorrect in several parts. The first condition is not even finished, it should say if (*(arrPtr i) % 3 == 0
, and the last condition does not check properly if the number is divisible by two. *(arrPtr i) % 2 != 0
would be the proper way to do that.
With all this combined, the final result should be something like this:
void charAlloc(){
char *arrPtr;
arrPtr = malloc(sizeof(char)*100);
int i;
for (i=0; i<100; i ){
if (i % 5 == 0){
*(arrPtr i) = 'a';}
else if (i % 3 == 0 && (i % 7 != 0) && (i % 2 !=0)){
*(arrPtr i) = 'b';}
else {
*(arrPtr i) = 'c';}
}
free(arrPtr);
}
I'd like to thank all the commenters for helping me understand this problem and I hope other programmers with issues similar to mine can find this useful.