This question already has answers here:
Is it possible to allocate array inside function and return it using reference?
(3 answers)
How can I allocate memory for array inside a function
(5 answers)
How to use pointers to allocate an array inside another function
(2 answers)
Allocate memory 2d array in function C
(8 answers)
Closed 5 years ago.
I'm trying to pass a pointer from main to a function I wrote, which suppose to allocate memory with the size integer and receive input from the user.
Now I know I'm doing something wrong because the pointer doesn't change back in the main function. could someone tell me what exactly I did wrong?
int rows, *newCol=NULL // the pointer inside main();//rows is the size of the array.
the function:
void buildArr(int *newCol, int rows);
void buildArr(int *newCol, int rows)
{
int i;
newCol = (int*)malloc(sizeof(int)*rows);
for (i = 0; i<rows; i++)
{
printf("enter the value of the newCol:\n");
printf("value #%d\n", i + 1);
scanf("%d", &newCol[i]);
}
}
The pointer shouldn't change in the callee. C is pass by value.
Pass the address of the pointer variable
Call it like
buildArr(&newCol,rows);
...
...
void buildArr(int **newCol, int rows)
{
int i;
*newCol = malloc(sizeof(int)*rows);
...
scanf("%d", &(*newCol)[i]);
}
// nothing is returned.
}
Or return the address of the allocated chunk
newCol = buildArr(newCol, rows);
...
...
int* buildArr(int *newCol, int rows)
{
int i;
newCol = malloc(sizeof(int)*rows);
...
scanf("%d", &newCol[i]);
...
return newCol;
}
Related
This question already has answers here:
Why can't we use double pointer to represent two dimensional arrays?
(6 answers)
Closed 3 years ago.
I am very new to C, and I am trying to get a int **data to represent a matrix of integers.
I first created an array of arrays, then I tried referencing the pointer of pointer to that array like so:
int **pointer;
int data[num_rows][num_cols];
pointer = (int**) data[0];
However I get a warning: cast to pointer from integer of a different size.
Can someone please help me understand what is going on, and how can I assign an array to int **pointer? (I have to use the double pointer)
The line int data[num_rows][num_cols]; does not actually declare an "array of arrays!" Rather, it declares a single array with two dimensions - in memory, this will be a single block of data, of size num_rows x num_cols x sizeof(int).
To get an "array of arrays" that you can access using a 'double pointer', you generally have to use the malloc function. Something like the following:
int **pointer = malloc(num_rows * sizeof(int*)); // allocate an array of pointers
for (int i = 0; i < num_rows; ++i) {
pointer[i] = malloc(num_cols * sizeof(int)); // allocate each row array
}
You can then access any [row][column] element via the double pointer:
pointer[row][column] = 1234;
When you've finished with the array(s), be sure to free the memory, like this:
for (int i = 0; i < num_cols; ++i) {
free(pointer[i]); // free each row array
}
free(pointer); // free the array of arrays
Alternatively, given your int data[num_rows][num_cols]; you could avoid the malloc calls inside the for loop, as follows:
int **pointer = malloc(num_rows * sizeof(int*)); // allocate an array of pointers
for (int i = 0; i < num_rows; ++i) {
pointer[i] = &data[i][0]; // Assign a pointer to the beginning of each row
}
Feel free to ask for further clarification and/or explanation.
This question already has answers here:
Returning an array from a function in C: Segmentation Fault [duplicate]
(3 answers)
How to access a local variable from a different function using pointers?
(10 answers)
Closed 4 years ago.
#include "stdafx.h"
#include <stdlib.h>
#include <time.h>
#define len 10
int *randomArray(void);
int main()
{
srand(time(NULL));
int *rArray = (int *)malloc(sizeof(int) * len);
rArray = randomArray();
for (int i = 0; i < len; i++) {
printf("%d ", *(rArray+i));
}
puts("");
free(rArray);
}
int *randomArray(void)
{
int array[len] = { 0 };
for (int i = 0; i < len; i++) {
array[i] = rand() % len;
}
return array;
}
Task is to create an array of ints and have a function fill that array with random numbers. The function randomArray() works just fine, but for some reason the assignment rArray = randomArray() doesn't work correctly, although some elements of rArray are valid numbers not gibberish. Also, the last main line free(rArray); crashes the program which is just mind numbing for me, it doesn't make any sense. If I remove the line the program doesn't crash but we all know you need to free() a malloc()-ed array.
The primary problem here is, array is a local variable in the randomArray() function scope. Once the function returns, the returned address becomes invalid. Any further attempt to use the memory will lead to undefined behavior.
Moreover, from your approach, you are trying to overwrite the allocated memory by the address being returned from the function call, which will cause memory leak. Rather, change your design, pass the allocated memory to the function as the argument and just fill the elements using the rand() call.
The randomArray return a pointer to the first element of the local array array.
That pointer becomes invalid immediately once the function returns as the variable goes out of scope. Using it in any way will lead to undefined behavior.
What makes it even worse is that you reassign the pointer rArray, making you lose the original memory you allocated. That means your call to free again will lead to UB.
To solve both problems, pass the pointer and the size as arguments to the randomArray function:
void randomArray(int *array, int size)
{
for (int i = 0; i < size; ++i)
{
array[i] = rand() % size;
}
}
int *randomArray(void)
{
int array[len] = { 0 };
//...
return array;
}
array goes out of scope at } and accessing this returned pointer is UB.
Moreover rArray = randomArray(); leaks memory since now you cannot free the malloc'd memory. You should pass the rArray to a function, which will be responsible for filing it.
In randomArray() function, you are returning the array that is allocated on stack. That array will be freed when returning from randomArray() function. Instead, you can do this:
void randomArray(int * array)
{
// Remove this int array[len] = { 0 };
for (int i = 0; i < len; i++) {
array[i] = rand() % len;
}
// Remove this .. return array;
}
And call randomArray(rArray) from main()
This question already has answers here:
Initializing a pointer in a separate function in C
(2 answers)
C Programming: malloc() inside another function
(9 answers)
Closed 5 years ago.
In the main function, I have some null pointer like
double *data_1;
This pointers are passed as argument to other function which determine how many components must have data_1 and uses malloc to assign a memory block and store information:
void function(double *data) {
...
data = (double *) malloc((size_t) (Ndata) * sizeof(double));
for(i = 0; i < (Ndata); i++) {
data[i] = sys->points[i][coordinate];
}
}
This code isn't working. I used GDB to examine bug and I encounter that inside function() the assignment works, but when execution returns to the main() function, the array data_1 wasn't modified although the memory to which it points is exactly the same to which points "data" argument in function().
Why is this happening?
The pointer you passed to your function is passed by value. It is copied to the parameter data. Inside you are allocating memory to data which will make it to point to the allocated memory instead of the pointer you passed. Any modification done to this pointer is not reflected to the pointer you passed. You need to return the pointer to the allocated memory.
double *function() {
...
double *data = malloc((size_t) (Ndata) * sizeof(double));
for(i = 0; i < (Ndata); i++) {
data[i] = sys->points[i][coordinate];
}
return data;
}
This question already has answers here:
Returning Arrays/Pointers from a function
(7 answers)
Closed 8 years ago.
I was trying to pass the array address from the function to the main function that's happening perfectly. But when I dereference the address in main(), I am getting junk values. I am guessing that the variables in the array_address memory lives only within the scope of the function. If this is the case, how do you return an array generated within a function to another function?
Here's my code:
int* letssee(int something)
{
int* array_address;
int a[10], i=0;
array_address = &a[0];
for (i; i<something;i++)
{
*(array_address+i) = i;
printf("\n%p, %d",(array_address+i), *(array_address+i));
}
return array_address;
}
int main()
{
int i= 5,j;
int* catch_address;
catch_address = letssee(i);
printf("\n");
for (j= 0; j<i; j++)
{
printf("%p, %d\n", (catch_address+j),*(catch_address+j));
}
return 0;
}
you can't return an array defined in a function as it is allocated on the stack and will disappear after the function has finished. Instead you allocate memory
int *array_address = malloc(sizeof(int) * 10);
however, you have to manage the memory, meaning you have to "free" it when you are finished with it, otherwise you will leak memory
The other approach is to pass the memory preallocated into a function (whether it be via malloc or the stack or global)
int* letsee(int something, int* array_address, int count);
if you simply make the array static, you are effectively making a global variable, multiple calls to the function will return the SAME address and may cause strange behaviour if you are expecting new arrays for each call.
This question already has answers here:
Using malloc for allocation of multi-dimensional arrays with different row lengths
(8 answers)
Closed 9 years ago.
I have a structure to store information in a 2D array:
struct slopes {
int size;
int ** slope_array;
};
I malloc the required memory for the structure(the array has dimensions of s*s):
struct slopes * slope=malloc(sizeof(struct slopes));
slope->size=s;
slope->slope_array=malloc(sizeof(int *)*s);
int i;
for(i=0;i<s;i++) {
slope->slope_array=malloc(sizeof(int)*s);
}
But lines such as these seem to throw segmentation errors:
slope->slope_array[0][0]=3;
Can someone see what I'm doing wrong?
In your for loop, you need to initialize slope->slope_array[i], not slope->slope_array:
for (i = 0; i < s; i++) {
slope->slope_array[i] = malloc(sizeof(int)*s);
}
Note: if you had cast the return call from malloc to an int *, the compiler would have warned you about this error...
There is a simple bug in your code, in the for loop do not assign the pointer returned by malloc to slope->slope_array, but to slope->slope_array[i]
slope->slope_array[i] = malloc(sizeof(int) * s);