So just like in python list I wanted to try and implement using c (I am new to c programming). This is my code
// File name:- list.c
#include <stdio.h>
#include <stdlib.h>
#include "l.h"
int main()
{
int myNumbers[] = {25, 50, 75, 100};
// int length = len(myNumbers);
push(myNumbers, 200, len(myNumbers));
for(int i = 0; myNumbers[i]; i++){
printf("array[%d] = %li\n", i, myNumbers[i]);
};
len(myNumbers);
return 0;
}
// File name:- l.c
#include "l.h"
#include <stdio.h>
int len(int arr[])
{
int i;
for(i = 0; arr[i]!='\0'; i++){
continue;
};
printf("Length is: %d\n", i);
return i;
}
void push(int list[], int value, int length)
{
// int length = len(list);
list[length] = value;
}
The above code does give me the result I expect, i.e
Length is: 4
array[0] = 25
array[1] = 50
array[2] = 75
array[3] = 100
array[4] = 200
Length is: 5
Whereas when int myNumbers[] = {25, 50, 75, 100, 125};
or anything more than 4 values in the array...
The Result is given unexpected random values like:-
Length is: 5
array[0] = 25
array[1] = 50
array[2] = 75
array[3] = 100
array[4] = 125
array[5] = 200
array[6] = 2782528512
array[7] = 1952226512
array[8] = 1
Length is: 9
How to fix this issue? I had even tried by directly passing the length and even calling the function without passing the length, but none of them worked... I went through the code for any logic error, I wasn't able to find any..
I expect this as my result...
Length is: 5
array[0] = 25
array[1] = 50
array[2] = 75
array[3] = 100
array[4] = 125
array[5] = 200
Length is: 6