Unable to access values while passing 2-D pointer - c

I have the following code :
int allocationMatrix[2+ 1][1+ 1];
allocationMatrix[0][0] = 2;
allocationMatrix[0][1] = 1;
buildAllocationMatrix(flowNProcess, allocationMatrix);
The buildAllocationMatrix function is declared like:
void buildAllocationMatrix(FlowNProcess *flowNProcess, int *allocationMatrix)
inside it, if I check the value of *(allocationMatrix+1), it gives 0 but the assignment
before calling the function is allocationMatrix[0][1] = 1; Not sure why its giving 0
It should return 1. What could be the reason for this?

Pass int **allocationMatrixinside function since it is 2D array.
(becauseint *allocationMatrix is interpreted as passing address of 1D array) .
And access it by
*(*(allocationMatrix+0)+1).
(Reason: by using*(allocationMatrix+0) you will get address of 0th row and in order to get address of 0th row 1st column we can use (*(allocationMatrix+0)+1) thus to get element of that position dereference it as
*(*(allocationMatrix+0)+1) ).
While accessing you can skip zero.

Related

How to reach an array that an array of pointers points to?

I'm trying to create an array of pointers, in which each pointer points to the start of an array (which is basically also an array of pointers)
I've tried the following:
//declarations:
int* all_paths_of_size_r= (int*)malloc(p_num*sizeof(int)); //p_num is the number of possible paths of size r
int* path = (int*)malloc(r*sizeof(int));
I'm using both of them in recurrsive function in which i wrote:
*(all_paths_of_size_r + place_in_arr) = path[0];
free(path);
place_in_arr++;
adds++; // this is an int that tells me if there are no more possible paths of size r so that i can free the last malloc I created within the function
int* path = (int*)malloc(r*sizeof(int));
if(adds==how_many_paths_of_size_r_could_be_generated_of_set_N(r, N)) //set N is the numbers from 0 to N-1
free(path);
now, I'm trying to reach each one of these arrays that are pointed at by all_paths_of_size_r (I mean I’m trying to reach every array to check if the last number of it is x), how do I do so?

Try to pass an array of int in a custom function, doens't get the content of the array in the custom function

I try to create an array of int in C, and then, use it in a custom function :
int a[] = {1,3,5,7,9};
int* new_a = extract(a, 2, 4);
// ...
int *extract(int* T, int a, int b){
int lenght_T = getLenghtOfSimpleArray(T);
...
}
I use the IDE visual code, when I inspect the code through the degugger, I get :
I don't understand why, in the debugger, the value of T is not {1,3,5,7,9}...
Where is my mystake ?
When you pass an array to a function it gets degraded to a pointer that points to the first element of the array. That means, T is an address in memory, so the big hex value shown in the debugger looks normal.
The debugger also shows *T, which is the value where the pointer points to, i.e. the first element of the array. The value is 1 as expected.
There is no way to find out the size/length of an array passed to a function this way, so it is not possible to make a working function getLenghtOfSimpleArray, except if you define an "invalid" value (sentinel value) which must be put to the last element of the array. In the general case, the caller must pass the size of the array to the function in addition to the array name = pointer to the first element.
example code with passing the array length
int a[] = {1,3,5,7,9};
int* new_a = extract(a, sizeof(a) / sizeof(a[0]), 2, 4);
int *extract(int* T, size_t length, int a, int b){
int lenght_T = getLenghtOfSimpleArray(T);
...
}
Arrays are not pointers. Pointers are not arrays.
T is not an array, it's a pointer to the first element. As you can see from your debugger, *T is 1, which is that first element.
Most debuggers support watches such as T[1] etc if you wish to inspect individual items beyond the first. Or they have a "range" feature that allows you to view a number of items.
In C, arrays are just values in the memory right next to each other, and the pointer only points to the first entry.
So in your case if you want to access the other values you have to access them with T[index]
The debugger only shows the first value of the array in this case.

Function to remove a struct from an array doesn't work if I pass the array as a parameter

I have a weird problem and I don't know the reason, so I can't think of a solution to fix it.
My problem:
I have a removeEntry function with a array of structs as parameter, but somehow this function doesn't work.
In an earlier version of my code, I declared my array of structs outside the main function (outside every function), and it worked then. But since I now create my array of struct in my main function, I have to give it as parameter, and now my removeEntry function doesn't work.
Code that isn't working:
void removeEntry(struct entry entries[])
{
int entryNumber;
int nrBytes = sizeof(entries);
int arrayLength = nrBytes / sizeof(entries[0]);
printf("\nEnter entry number to delete: ");
scanf("%d",&entryNumber);
while (scanfOnlyNumber(entryNumber) == false || entryNumber == 0 || entries[entryNumber].entry_number == 0)
{
printf("\nEnter a legit entry number to delete: ");
scanf("%d", &entryNumber);
// Tell the user that the entry was invalid
}
int i = 0;
for(i = entryNumber; i < arrayLength - 1; i++)
{
entries[i] = entries[i + 1]; //removes element and moves every element after that one place back.
}
updateEntryNumber(entries);
printf("\nEntry %d removed succesfully, and entry numbers updated!\n", entryNumber);
}
My teacher told me that my arraylength calculation doesn't work when I create my array of structs inside my main function (what I do now),
but I can't tell why it doesn't work. If anybody can explain that, then I might be able to fix my removeEnty problem by myself.
If anyone wants the working code (where I don't give my array as parameter, because I create my array outside every function), then tell me and I will post it.
Problem
When you pass an array to a function, you don't pass the entire array, instead you pass a pointer to the array. Hence, when you do int nrBytes = sizeof(entries); you're actually getting the size of pointer variable rather than the size of array.
Solution
Pass your array length along with a pointer to the array to the function, something like this:
void removeEntry(struct entry entries[], int arrayLength){
// your code
}
int nrBytes = sizeof(entries); // basically size of struct node *
int arrayLength = nrBytes / sizeof(entries[0]);
In this sizeof(entries) will give size of struct pointer , and not the array , and also in second statement , it wont correctly .
This is because array decays into pointer after passing it to function and referring it .
What you need to do is calculate number of elements in struct array in main and then pass it to the function .
void removeEntry(struct entry entries[],int arrayLength);
Calculate arrayLength in main as you do.
if you compile your example, you will probably see a warning like this one:
warning: sizeof on array function parameter will return size of 'entry *' instead of 'entry []' [-Wsizeof-array-argument]
As noted in the answer by V. Kravchenko, this suggests that nrBytes will contain merely the size of the pointer, while sizeof(entries[0]) returns the "true" size of the entire structure. Therefore, arrayLength will be most probably zero.
You should pass array's size to function, because int nrBytes = sizeof(entries); is always 4 or 8 (on x64 systems). It's just pointer's size.
int nrBytes = sizeof(entries);
Arrays of any type (even arrays of structs) decay into pointers when passed to a function. The lenght of this pointer is always fixed and gives no indication as to the lenght whatsoever. So pass the lenght with the function call.

Using lfind to retrieve the index of an element

With an array of a certain type of element. Is there a way to use lfind to retrieve the index of an element instead of a pointer to the element?
You have that with the pointer.
Subtract the start of the array from the returned pointer - that's the index.
Edit to explain more, just in case:
When you declare an array
int foo[5];
foo without an index is a pointer to the first element
foo == &foo[0]
So if I have a pointer to an element in the array
int *p = &foo[4];
I can get the index with:
int index = p - foo;

C Programming: Pointer to a row of a 2D array?

I wrote a function that returns a pointer to a 1D array. The function prototype is:
double* NameFunction (int,double*,double*)
The function seems to work fine with 1D array.
Here's the question: I'd like to use the function to fill one row of a 2D array.
How do I write in the calling function a pointer to the row of the 2D array to fill?
Can I use the same pointer structure to indicate a row of a 2D array as argument?
Yes just pass the name of the 2D array with the first index filled in:
NameFunction (12121212,&array[0],some pointer here) // for example if you want to pass the first row
A variable pointing to an array in C always contains just an address location i.e., the pointer to the starting of the array. So, whatever the array type, it just needs a pointer which is a *.So this function should work as it is now.
But you may need to change some programming logic.
You can take double foo[20] as 1×20 array, or you can take it as two-dimensional 4×5 array. Then you have the coordinates like this:
foo foo+1 foo+2 foo+3 foo+4
foo+5 foo+6 foo+7 foo+8 foo+9
foo+10 foo+11 foo+12 foo+13 foo+14
foo+15 foo+16 foo+17 foo+18 foo+19
So if you have a function that returns double *, you can pass it (or make it return) foo + 5*n to point at row n.
#define ROW_LEN 5
#define ROWS 4
void fillRow(double * row)
{
int i;
for (i = 0; i < ROW_LEN; i++)
{
row[i] = 12;
(row + i) = 12; // this is the same thing written differently
}
}
double arr[ROW_LEN * ROWS];
fillRow(arr + 2 * ROW_LEN); // fill third row
Note that C does not do any range checking at all, so if you are not careful and accidentally to something like arr[627] = 553 somewhere in your code, it's going to blindly overwrite everything that is at the computed address in the memory.

Resources