changing adress of pointer created using malloc - c

I am trying to understand how malloc and pointer works.
#include <stdio.h>
#include <stdlib.h>
int main() {
int *p;
int b = 15;
p = (int *)malloc(sizeof(int) * 10);
for (int i = 0; i < 5; i++) {
p + i = &b;
}
}
The above code gives error
expression is not assignable
p + i = &b;
As far as I understand, malloc gives the starting address of the memory allocated in heap which I typecast to hold the address of integers. So technically, p + i should be able to hold any integer address, but the code throws an error. Can you please explain why this is wrong.
Thanks

The line of code p = (int *)malloc(sizeof(int) * 10); means that the pointer p is assigned the address of the first element of the dynamically allocated array with malloc(),which has allocated an int array consisting of 10 elements.
If you want to assign 5 of these elements the value of b then you write:
for (int i = 0; i < 5; i++) {
p[i] = b;
}
If however you want an array of 10 integer pointers and want to assign 5 of them the address of b,then you write:
int **pointer = (int **)malloc(sizeof(int *) * 10);
for (int i = 0; i < 5; i++) {
pointer[i] = &b;
}
Don't forget to free dynamically allocated memory when you finish.

p + i is pointing to an address on your memory, the same as &(p[i]). You can't change the address of the memory, so that's why the compiler is saying the expression is not assignable.
If you want to save an int on that address you need to use *(p+i) = b.
But if you want to save the address of an int you need an array which holds int*, so you need to declare p as an int** and allocate its memory with the sizeof(int*). That way your code would look like this:
#include <stdio.h>
#include <stdlib.h>
int main() {
int **p;
int b = 15;
p = (int**)malloc(sizeof(int*) * 10);
for (int i = 0; i < 5; i++) {
*(p + i) = &b;
}
}

Related

different ways to declare a matrix c

I don't really understand why method 1 works but not method 2. I don't really see why it works for characters and not an int.
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
/// WORK (METHODE 1)
char **string_array = malloc(sizeof(char **) * 10);
string_array[0] = "Hi there";
printf("%s\n", string_array[0]); /// -> Hi there
/// DOES NOT WORK (METHODE 2)
int **int_matrix = malloc(sizeof(int **) * 10);
int_matrix[0][0] = 1; // -> Segmentation fault
/// WORK (METHODE 3)
int **int_matrix2 = malloc(sizeof(int *));
for (int i = 0; i < 10; i++)
{
int_matrix2[i] = malloc(sizeof(int));
}
int_matrix2[0][0] = 42;
printf("%d\n", int_matrix2[0][0]); // -> 42
}
In terms of the types, you want to allocate memory for the type "one level up" from the pointer you're assigning it to. For example, an int pointer (an int*), points to one or more ints. That means, when you allocate space for it, you should allocate based on the int type:
#define NUM_INTS 10
...
int* intPtr = malloc(NUM_INTS * sizeof(int));
// ^^ // we want ints, so allocate for sizeof(int)
In one of your cases, you have a double int pointer (an int**). This must point to one or more int pointers (int*), so that's the type you need to allocate space for:
#define NUM_INT_PTRS 5
...
int** myDblIntPtr = malloc(NUM_INT_PTRS * sizeof(int*));
// ^^ "one level up" from int** is int*
However, there's an even better way to do this. You can specify the size of your object it points to rather than a type:
int* intPtr = malloc(NUM_INTS * sizeof(*intPtr));
Here, intPtr is an int* type, and the object it points to is an int, and that's exactly what *intPtr gives us. This has the added benefit of less maintenance. Pretend some time down the line, int* intPtr changes to int** intPtr. For the first way of doing things, you'd have to change code in two places:
int** intPtr = malloc(NUM_INTS * sizeof(int*));
// ^^ here ^^ and here
However, with the 2nd way, you only need to change the declaration:
int** intPtr = malloc(NUM_INTS * sizeof(*intPtr));
// ^^ still changed here ^^ nothing to change here
With the change of declaration from int* to int**, *intPtr also changed "automatically", from int to int*. This means that the paradigm:
T* myPtr = malloc(NUM_ITEMS * sizeof(*myPtr));
is preferred, since *myPtr will always refer to the correct object we need to size for the correct amount of memory, no matter what type T is.
Others have already answered most of the question, but I thought I would add some illustrations...
When you want an array-like object, i.e., a sequence of consecutive elements of a given type T, you use a pointer to T, T *, but you want to point to objects of type T, and that is what you must allocate memory for.
If you want to allocate 10 T objects, you should use malloc(10 * sizeof(T)). If you have a pointer to assign the array to, you can get the size from that
T * ptr = malloc(10 * sizeof *ptr);
Here *ptr has type T and so sizeof *ptr is the same as sizeof(T), but this syntax is safer for reasons explained in other answers.
When you use
T * ptr = malloc(10 * sizeof(T *));
you do not get memory for 10 T objects, but for 10 T * objects. If sizeof(T*) >= sizeof(T) you are fine, except that you are wasting some memory, but if sizeof(T*) < sizeof(T) you have less memory than you need.
Whether you run into this problem or not depends on your objects and the system you are on. On my system, all pointers have the same size, 8 bytes, so it doesn't really matter if I allocate
char **string_array = malloc(sizeof(char **) * 10);
or
char **string_array = malloc(sizeof(char *) * 10);
or if I allocate
int **int_matrix = malloc(sizeof(int **) * 10);
or
int **int_matrix = malloc(sizeof(int *) * 10);
but it could be on other architectures.
For your third solution, you have a different problem. When you allocate
int **int_matrix2 = malloc(sizeof(int *));
you allocate space for a single int pointer, but you immediately treat that memory as if you had 10
for (int i = 0; i < 10; i++)
{
int_matrix2[i] = malloc(sizeof(int));
}
You can safely assign to the first element, int_matrix2[0] (but there is a problem with how you do it that I get to); the following 9 addresses you write to are not yours to modify.
The next issue is that once you have allocated the first dimension of your matrix, you have an array of pointers. Those pointers are not initialised, and presumably pointing at random places in memory.
That isn't a problem yet; it doesn't do any harm that these pointers are pointing into the void. You can just point them to somewhere else. This is what you do with your char ** array. You point the first pointer in the array to a string, and it is happy to point there instead.
Once you have pointed the arrays somewhere safe, you can access the memory there. But you cannot safely dereference the pointers when they are not initialised. That is what you try to do with your integer array. At int_matrix[0] you have an uninitialised pointer. The type-system doesn't warn you about that, it can't, so you can easily compile code that modifies int_matrix[0][0], but if int_matrix[0] is pointing into the void, int_matrix[0][0] is not an address you can safely read or write. What happens if you try is undefined, but undefined is generally was way of saying that something bad will happen.
You can get what you want in several ways. The closest to what it looks like you are trying is to implement matrices as arrays of pointers to arrays of values.
There, you just have to remember to allocate the arrays for each row in your matrix as well.
#include <stdio.h>
#include <stdlib.h>
int **new_matrix(int n, int m)
{
int **matrix = malloc(n * sizeof *matrix);
for (int i = 0; i < n; i++)
{
matrix[i] = malloc(m * sizeof *matrix[i]);
}
return matrix;
}
void init_matrix(int n, int m, int **matrix)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
matrix[i][j] = 10 * i + j + 1;
}
}
}
void print_matrix(int n, int m, int **matrix)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
int main(void)
{
int n = 3, m = 5;
int **matrix = new_matrix(n, m);
init_matrix(n, m, matrix);
print_matrix(n, m, matrix);
return 0;
}
Here, each row can lie somewhere random in memory, but you can also put the row in contiguous memory, so you allocate all the memory in a single malloc and compute indices to get at the two-dimensional matrix structure.
Row i will start at offset i*m into this flat array, and index matrix[i,j] is at index matrix[i * m + j].
#include <stdio.h>
#include <stdlib.h>
int *new_matrix(int n, int m)
{
int *matrix = malloc(n * m * sizeof *matrix);
return matrix;
}
void init_matrix(int n, int m, int *matrix)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
matrix[m * i + j] = 10 * i + j + 1;
}
}
}
void print_matrix(int n, int m, int *matrix)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
printf("%d ", matrix[m * i + j]);
}
printf("\n");
}
}
int main(void)
{
int n = 3, m = 5;
int *matrix = new_matrix(n, m);
init_matrix(n, m, matrix);
print_matrix(n, m, matrix);
return 0;
}
With the exact same memory layout, you can also use multidimensional arrays. If you declare a matrix as int matrix[n][m] you will get what amounts to an array of length n where the objects in the arrays are integer arrays of length m, exactly as on the figure above.
If you just write that expression, you are putting the matrix on the stack (it has auto scope), but you can allocate such matrices as well if you use a pointer to int [m] arrays.
#include <stdio.h>
#include <stdlib.h>
void *new_matrix(int n, int m)
{
int(*matrix)[n][m] = malloc(sizeof *matrix);
return matrix;
}
void init_matrix(int n, int m, int matrix[static n][m])
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
matrix[i][j] = 10 * i + j + 1;
}
}
}
void print_matrix(int n, int m, int matrix[static n][m])
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
int main(void)
{
int n = 3, m = 5;
int(*matrix)[m] = new_matrix(n, m);
init_matrix(n, m, matrix);
print_matrix(n, m, matrix);
int(*matrix2)[m] = new_matrix(2 * n, 3 * m);
init_matrix(2 * n, 3 * m, matrix2);
print_matrix(2 * n, 3 * m, matrix2);
return 0;
}
The new_matrix() function returns a void * because the return type cannot depend on the runtime arguments n and m, so I cannot return the right type.
Don't let the function types fool you, here. The functions that take a matrix[n][m] argument do not check if the matrix has the right dimensions. You can get a little type checking with pointers to arrays, but pointer decay will generally limit the checking. The last solution is really only different syntax for the previous one, and the arguments n and m determines how the (flat) memory that matrix points to is interpreted.
The method 1 works only becuse you assign the char * element of the array string_array with the reference of the string literal `"Hi there". String literal is simply a char array.
Try: string_array[0][0] = 'a'; and it will fail as well as you will dereference not initialized pointer.
Same happens in method 2.
Method 3. You allocate the memory for one int value and store the reference to it in the [0] element of the array. As the pointer references the valid object you can derefence it (int_matrix2[0][0] = 42;)

Invalid operands to binary - (have 'int' and 'int *')

I've a problem when I run the program which is:
invalid operands to binary - (have 'int' and 'int *')
Since I defined a dynamic array **engelCikacagiYer then I tried to make an operation on karakterHP
int karakterHP = 100;
int **engelCikacagiYer;
engelCikacagiYer = malloc(engelSayisi * sizeof(int));
for(i = 0; i < engelSayisi; i++){
engelCikacagiYer[i] = (rand() % (100 - 5 + 1) + 5);
}
for(i = parkurUzunlugu.Baslangic; i < parkurUzunlugu.Bitis; i++){
if (asal(engelCikacagiYer)) {
karakterHP -= engelCikacagiYer[i];
printf("%d\t", karakterHP);
}
}
This piece of code:
int **engelCikacagiYer;
engelCikacagiYer = malloc(engelSayisi*sizeof(int));
Is not correct, to allocate memory to a double pointer, aka pointer to pointer you need to allocate using the size it points to and that is pointer to int so you would need:
engelCikacagiYer = malloc(engelSayisi*sizeof(int*));
Or better yet:
engelCikacagiYer = malloc(engelSayisi*sizeof(*engelCikacagiYer));
Later you try to assign an int value to a engelCikacagiYer[i] which is a pointer variable not an int variable, hence the error.
If you really need a double pointer, after the first malloc you will need to allocate memory for each engelCikacagiYer[i] pointer:
for(int i = 0; i < engelSayisi; i++){
engelCikacagiYer[i] = malloc(sizeof(**engelCikacagiYer));
}
And assing values as if it was a 2D array (I mean using the same notation), example:
engelCikacagiYer[i][0] = (rand()%(100-5+1)+5);
or
*engelCikacagiYer[i] = (rand()%(100-5+1)+5);
Here is a simplified possible implementation of a correct allocation:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int **engelCikacagiYer;
engelCikacagiYer = malloc(100 * sizeof(*engelCikacagiYer)); //check allocation for errors
for(int i = 0; i < 100; i++){
engelCikacagiYer[i] = malloc(sizeof(**engelCikacagiYer)); //check allocation
*engelCikacagiYer[i] = (rand() % (100 - 5 + 1) + 5);
}
for (int i = 0; i < 100; i++) //test print
{
printf("%d ", *engelCikacagiYer[i]);
}
}
In any case, for the code you present using a single pointer to int would also be a valid (and simpler) solution.
Change int **engelCikacagiYer; to int *engelCikacagiYer;.
By your code it seems you want a dynamic array of ints, not a dynamic array of int pointers.

Why does a pointer to a multidimensional array return segmentation fault when accessed after passing the pointer to a function?

So I don't really know what this problem is really called so searching and googling leads to different answers which does not answer my question.
This is the code:
#include <stdio.h>
#include <stdlib.h>
void gen_matrix(int **array, int rm, int cm) {
// int ** array;
int r, c;
array = (int **) malloc(sizeof(int *) * rm);
for (int r = 0; r < rm; ++r) {
array[r] = (int *) malloc(sizeof(int) * cm);
for (int c = 0; c < cm; ++c) {
array[r][c] = 1;
} // c
} // r
}// gen_matrix
int main() {
int **a;
gen_matrix(a, 2, 2);
printf("%d", a[0][0]);
return 0;
}
The problem is that printf() in main() returns Segmentation Fault. What I found out is that the address that the pointer a in main() points to does not change when malloc() is used inside gen_matrix().
In gen_matrix(), I can access the array just fine, but after I return to main(), the pointer a does not point to the array malloc() created.
Thank you.
You are losing the update to array when gen_matrix() returns, because you are not passing it the address of a. You could add an extra indirection level by passing in the address of a to gen_matrix(), but it would be cleaner to just have gen_matrix() return the malloced address and assign it to a in main():
int **gen_matrix(int rm, int cm) {
int ** array;
array = malloc(sizeof(*array) * rm);
for (int r = 0; r < rm; ++r) {
array[r] = malloc(sizeof(*(array[r])) * cm);
for (int c = 0; c < cm; ++c) {
array[r][c] = 1;
} // c
} // r
return array;
}// gen_matrix
int main() {
int **a;
a = gen_matrix(2, 2);
printf("%d", a[0][0]);
return 0;
}
Also, it's not a good idea to cast the return from malloc() and it is preferable to dereference the pointer the memory is being assigned to to get the proper size for sizeof().
And you should of course free() the memory before exiting.
When you call your function the parameter int ** array is the "array itself". What you need is a reference to it, either with one more level of pointer indirection or a C++-style reference. So, what you do is you modify the function to accept a triple-pointer:
void gen_matrix(int ** * array, int rm, int cm) {
and when you call it you also get the address of the "pointer to the matrix":
gen_matrix(&a, 2, 2);
of course you have to modify the code in the function to take care of that extra indirection:
*array = (int **) malloc(sizeof(int *) * rm);
and in the other two places as well.

dynamic allocation of array of pointers

The following code gives a segmentation fault. I am not able to figure out as to why. Please see..
#include <stdio.h>
#include <stdlib.h>
int main()
{
int **ptr;
int *val;
int x = 7;
val = &x;
*ptr = (int *)malloc(10 * sizeof (*val));
*ptr[0] = *val;
printf("%d\n", *ptr[0] );
return 0;
}
on debugging with gdb, it says:
Program received signal SIGSEGV, Segmentation fault.
0x0804843f in main () at temp.c:10
*ptr = (int *)malloc(10 * sizeof (*val));
Any help regarding the matter is appreciated.
int **ptr;
*ptr = (int *)malloc(10 * sizeof (*val));
First statement declares a double pointer.
Second dereferences the pointer. In order that you are able to dereference it the pointer should point to some valid memory. it does not hence the seg fault.
If you need to allocate enough memory for array of pointers you need:
ptr = malloc(sizeof(int *) * 10);
Now ptr points to a memory big enough to hold 10 pointers to int.
Each of the array elements which itself is a pointer can now be accessed using ptr[i] where,
i < 10
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int **ptr;
int x;
x = 5;
ptr = malloc(sizeof(int *) * 10);
ptr[0] = &x;
/* etc */
printf("%d\n", *ptr[0]);
free(ptr);
return 0;
}
See the below program, perhaps, it helps to understand better.
#include<stdio.h>
#include <stdlib.h>
int main(){
/* Single Dimention */
int *sdimen,i;
sdimen = malloc ( 10 * sizeof (int));
/* Access elements like single diminution. */
sdimen[0] = 10;
sdimen[1] = 20;
printf ("\n.. %d... %d ", sdimen[0], sdimen[1]);
/* Two dimention ie: **Array of pointers.** */
int **twodimen;
twodimen = malloc ( sizeof ( int *) * 10);
for (i=0; i<10; i++) {
twodimen[i] = malloc (sizeof(int) * 5);
}
/* Access array of pointers */
twodimen[0][0] = 10;
twodimen[0][3] = 30;
twodimen[2][3] = 50;
printf ("\n %d ... %d.... %d ", twodimen[0][0], twodimen[0][3], twodimen[2][3]);
return 0;
}
Hope this helps.. ;).
Conceptually if you are using **ptr, then you need to alloacte memory for ptr & *ptr to defrence **ptr.
But in you case you are alloacting memory only for *ptr,if your compiler is smart enough
its alloacting memory for ptr(one pointer location) to link *ptr,hence it could able to link ptr->ptr->*ptr.Hence you are not getting Seg Fault.
include
include
int main()
{
int **ptr;
int *val;
int x = 7;
val = &x;
ptr = (int**)malloc(sizeof(int**));
*ptr = (int *)malloc(10 * sizeof (*val));
*ptr[0] = *val;
printf("%d\n", *ptr[0] );
return 0;
}
Above would work.
You can find the difference and understand the reason as well.
Bottom line you were de-referencing **ptr without allocating memory to it.

C - malloc array in function and then access array from outside

Here is how I malloc an int var and then access this var outside of the function
int f1(int ** b) {
*b = malloc(sizeof(int));
**b = 5;
}
int main() {
int * a;
f1(&a);
printf("%d\n", *a);
// keep it clean :
free(a);
return 0;
}
Using same logic above, how do I malloc a 1 dim array inside a function and then access it outside of the func?
Please help, I am bit confused with pointers to array.
In exactly the same way but with some different arithmetic. You can think of what you are doing now as allocating an array with one element. Just multiply sizeof(int) by the number of elements you want your array to have:
int f1(int ** b, int arrsize) {
*b = malloc(sizeof(int) * arrsize);
// then to assign items:
(*b)[0] = 0;
(*b)[1] = 1;
// etc, or you can do it in a loop
}
int main() {
int * a, i;
int size = 20;
f1(&a, size); // array of 20 ints
for (i = 0; i < size; ++i)
printf("%d\n", a[i]); // a[i] is the same as *(a + i)
// so a[0] is the same as *a
// keep it clean :
free(a);
return 0;
}
(untested, but I believe it'll work)
int f1(int ** b) {
*b = malloc(sizeof(int)*4);
(*b)[0] = 5;
(*b)[1] = 6;
(*b)[2] = 7;
(*b)[3] = 8;
}
int main() {
int * a;
f1(&a);
printf("%d %d %d %d\n", a[0], a[1], a[2], a[3]); // should be "5 6 7 8"
// keep it clean :
free(a);
return 0;
}
You are almost there *b = malloc(sizeof(int)); allocates space for a single int ( a bit pointless since the pointer is at least as big as this)
The more normal usage is *b = malloc(number_of_ints*sizeof(int));
Remember that the [] syntax just does the array maths for you (a+10) and a[10] point to exactly the same thing memory location, so you can allocate it using malloc, pass the poitner and refer to it as an array.
The only things about arrays and pointers that is complicated (apart from remembering when to use * and &) is that malloc() works in bytes, so you need to tell it the sizeof an int. But the int * it returns knows about ints so to get to the next value you only need to do a++ or a+1 or a[1] even though it is really 4 or 8 bytes different in value.
Instead of malloc()ing a single int, malloc the array.
int f1(int * b) {
b = malloc(ARRAY_LENGTH * sizeof(int));
*b = 5;
b[1] = 6;
*(b + 2) = 7;
}
You'll want to use a calloc call instead of malloc (See this: http://www.manpagez.com/man/3/calloc/)

Resources