I'm expecting for this code (second code) to run only 3 times. but it runs 6 on visual studio, and when I tried it on sololearn playground it run 4 times.
I've done other testing kind of like this code and the while loop never stops running. I thought that if the memory address did not hold any value it would be consider NULL, so it should return a 0, but it does not (for the first code).
well now I know why I'm wrong because is comparing the memory not the value inside the memory which makes sense why this code(first code) "never" stops.
///first code
int main() {
int* s = malloc(5 * sizeof(int));
int i = 0;
while(i < 5){
*(s + i) = i;
i++;
}
i = 0;
while(s + i != NULL)
{
printf("hello");
i++;
}
printf("%d", i);
return 0;
}
, but then why does the second code stops if it is also comparing the memory address?
//second code
#include <stdio.h>
#include <stdlib.h>
int main() {
int** s = malloc(3 * sizeof(int*));
int x = 0;
for(x = 0; x < 3; x++)
{
*(s + x) = malloc(1 * sizeof(int*));
}
int i = 0;
while( *(s + i) != NULL)
{
printf("hello");
i++;
}
printf("%d", i);
return 0;
}
And I guess the solution would be just to use a link list right?