If I allocated a multidimensional array dynamically and without using indexes ( [ i ] [ j ] ), how can I initialize it?
#include <stdio.h>
#include <stdlib.h>
#define ROWS 3
#define COLUMNS 4
int main(void)
{
int i,j;
char **v;
v = malloc(ROWS * sizeof(char*));
for (i = 0 ; i < ROWS ; i++)
*(v + i * sizeof(char*)) = malloc(COLUMNS * sizeof(char));
for (i = 0 ; i < ROWS ; i++)
for (j = 0 ; j < COLUMNS ; j++)
??? = 'a' + i * COLUMNS + j;
return 0;
}
Instead of ??? what do I have to put? Addresses aren't contiguous so I think this expression:
**(v+(i*COLUMNS+j)*sizeof(char))
isn't correct...
Thanks.
Do not multiply by the size of the type, pointer arithmetics is done in multiples of the base type.
You need to dereference like you do above, and then dereference again, like this
int i, j;
char **v;
v = malloc(ROWS * sizeof(char *));
if (v == NULL)
return -1;
for (i = 0 ; i < ROWS ; i++)
{
*(v + i) = malloc(COLUMNS * sizeof(char));
if (*(v + i) == NULL)
return -1;
for (j = 0 ; j < COLUMNS ; j++)
{
*(*(v + i) + j) = 'a' + i * COLUMNS + j;
}
}
return 0;
and don't forget to free().
So basically x[i] is equivalent to *(x + i) and you can apply it to the resulting pointer too.
NOTE: These are not strings, they need to be nul terminated to become strings.
If you insist on using sizeof this is how
int i, j;
char **v;
v = malloc(ROWS * sizeof(char *));
if (v == NULL)
return -1;
for (i = 0 ; i < ROWS ; i++)
{
*((unsigned char *) v + i * sizeof(char *)) = malloc(COLUMNS * sizeof(char));
if (*(v + i) == NULL)
return -1;
for (j = 0 ; j < COLUMNS ; j++)
{
*(*((unsigned char *) v + i * sizeof(char *)) + j) = 'a' + i * COLUMNS + j;
}
}
I will not use sizeof(char) as it's very redundant, the standard clearly states that sizeof(char) MUST be 1.
You are not creating a multi-dimensional array but an array of pointers. In your code, a possibility is to put *((*(v + i)) + j) in place of your ???.
Otherwise if you want the addresses to be contiguous like a multi-dimensional array you need to allocate all the memory in one malloc, assign it to v, and then use *(v + i*COLUMNS + j) to access it.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I can't understand what doing the row
*(m[i] + sizes[i] - 1) = n;
#include <stdio.h>
#include <stdlib.h>
#define MAXSTR 100
int main()
{
int i, j, k, n;
char str[MAXSTR];
printf("Enter amount of rows: ");
fgets(str, MAXSTR, stdin);
k = atoi(str);
int* sizes = (int * ) calloc(k, sizeof(int));
int* sum = (int * ) calloc(k, sizeof(int));
int** m = (int ** ) calloc(k, sizeof(int * ));
printf("Enter matrix:\n");
for (i = 0; i < k; i++)
{
fgets(str, MAXSTR, stdin);
char* sym = str;
while (1)
{
m[i] = (int * ) realloc(m[i], (++sizes[i]) * sizeof(int));
n = strtol(sym, & sym, 10);
sum[i] += n;
if (n)
{
*(m[i] + sizes[i] - 1) = n;
}
else
{
--sizes[i];
break;
}
}
}
printf("\nMatrix: \n");
for (i = 0; i < k; i++)
{
for (j = 0; j < sizes[i]; j++)
printf("%i ", *(m[i] + j));
printf("\n");
}
printf("\nSum of elements of row:\n");
for (i = 0; i < k; i++)
printf("#%i - %i\n", i + 1, sum[i]);
free(sizes);
free(sum);
free(m);
return 0;
m is the matrix. Or more formally, it appears to be an array of "rows". Where each row is an array of integers.
sizes[i] is the length of the row represented by m[i].
This expression
*(m[i] + sizes[i] - 1) = n;
Appears to assign the value n to the last index of the row identified by m[i]. Essentially, it's appending to the end of the reallocated array.
This entire block of code is a bit complex:
while (1)
{
m[i] = (int * ) realloc(m[i], (++sizes[i]) * sizeof(int));
n = strtol(sym, & sym, 10);
sum[i] += n;
if (n)
{
*(m[i] + sizes[i] - 1) = n;
}
else
{
--sizes[i];
break;
}
}
It could be simplified to just:
int rowsize = 0;
while (1)
{
n = strtol(sym, &sym, 10); // parse the next number in str
if (n == 0) // the row ends when 0 is read
{
break;
}
m[i] = (int *)realloc(m[i], (rowsize+1) * sizeof(int); // grow the row's size by 1
m[i][rowsize] = n;
sum[i] += n;
rowsize++;
}
sizes[i] = rowsize;
m[i] is a pointer to the first element in the i:th matrix row
sizes[i] is the current number of columns in row i
sizes[i] - 1 is the last element in row i
m[i] + sizes[i] - 1 is a pointer to the last element in row i
*(m[i] + sizes[i] - 1) is the last element in row i
When allocating memory in C the result should not be cast, so
int* sizes = (int * ) calloc(k, sizeof(int));
should be simply
int* sizes = calloc(k, sizeof(int));
Also, the rows of the matrix m are never freed; to free the entire matrix you would need
for (i = 0; i < k; i++) {
free(m[i]);
}
free(m);
To answer your question the statement *(m[i] + sizes[i] - 1) = n; assigns the value n to whatever m[i] + sizes[i] - 1 points to. m is a pointer to a pointer to an int, so m[i] is an address of an int pointer. sizes[i] - 1 is usually how you convert from a size to index, so it's an offset from that int pointer.
Here are some suggested changes (all but one implemented below):
Reduce variable scope but initialize sum to NULL before the first failure so it can be unconditionally deallocated
It is better user experience to just read the data and terminate with an empty line instead of asking for the user count upfront. Just update the count k as we go along. This eliminates atoi which does not do any error handling. If you want to crash the program due to being out of memory you have to provide the data not just large a count.
(not fixed) realloc of 1 element at a time, if the O(i^2) is a performance issue, keep track of size and capacity of sum. When size == capacity, realloc by some factor, say, 2. Optionally, realloc to size when when we finish reading data as we now have the actual number of lines k.
No point of printing the array you just entered, which means we can get rid of the m and sizes arrays
Deallocate sum if realloc fails by introducing a temporary sum2 variable that will be NULL on error, but sum will still point to previously allocated data
Check for under and overflow of n and sum
Use sizeof on variable instead of type so you can change type just one place if needed
Allow 0 values by passing in by using a separate pointer endptr than sym to strtol()
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#define CHECK(p, msg) if(!(p)) {\
printf("%s:%d %s\n", __FILE__, __LINE__, (msg));\
goto out;\
}
#define MAXSTR 100
int main() {
int k;
char str[MAXSTR];
int *sum = NULL;
printf("Enter matrix:\n");
for(int i = 0;; i++) {
fgets(str, MAXSTR, stdin);
char *sym = str;
int *sum2 = realloc(sum, (i + 1) * sizeof(*sum));
CHECK(sum2, "realloc failed");
sum = sum2;
int j;
for(j = 0;; j++) {
char *endptr;
long n = strtol(sym, &endptr, 10);
CHECK(n >= INT_MIN && n <= INT_MAX,\
"value truncated");
if(sym == endptr) {
break;
}
sym = endptr;
CHECK((n >= 0 && sum[i] <= INT_MAX - n) || \
(n < 0 && sum[i] >= INT_MIN - n),\
"sum truncated");
sum[i] += n;
}
if(!j) {
k = i;
break;
}
}
printf("Sum of elements of row:\n");
for (int i = 0; i < k; i++)
printf("#%i - %i\n", i + 1, sum[i]);
out:
free(sum);
return 0;
}
Example execution:
Enter matrix:
0 1 2
Sum of elements of row:
#1 - 3
I have a graph code written a year ago which does not work now (AFAIR it worked). The graph is implemented with a square matrix which is symmetric respectively to the diagonal. I have omitted a lot of code to keep it as clear as possible, and this is still enough for the error to persist.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct
{
int **matrix;
unsigned size;
} graph;
void init(graph *gptr, int *matrix[], unsigned size)
{
gptr->size = size;
gptr->matrix = malloc(gptr->size * sizeof(*gptr->matrix));
for (unsigned i = 0; i < gptr->size; i++)
gptr->matrix[i] = malloc(gptr->size * sizeof(**gptr->matrix));
for (unsigned i = 0; i < gptr->size; i++)
for (unsigned j = 0; j <= i; j++)
gptr->matrix[i][j] = gptr->matrix[j][i] = matrix[i][j];
}
void add_vertex(graph *gptr, unsigned vertex)
{
for (unsigned i = 1; i < gptr->size; i++)
if (gptr->matrix[i][0] == vertex) return;
gptr->size++;
gptr->matrix = realloc(gptr->matrix, gptr->size * sizeof(*gptr->matrix));
for (unsigned i = 0; i < gptr->size; i++)
/* ERROR */
gptr->matrix[i] = realloc(gptr->matrix[i], gptr->size * sizeof(**gptr->matrix));
gptr->matrix[gptr->size - 1][0] = gptr->matrix[0][gptr->size - 1] = vertex;
for (unsigned i = 1; i < gptr->size; i++)
gptr->matrix[gptr->size - 1][i] = gptr->matrix[i][gptr->size - 1] = -1;
}
#define EDGES 7
#define RANDOM(min, max) min + rand() / ((RAND_MAX - 1) / (max - min))
#define MIN -1
#define MAX 9
int **getMatrix(unsigned size)
{
int **matrix = malloc(size * sizeof(*matrix));
for (unsigned i = 0; i < size; i++)
{
matrix[i] = malloc((i + 1) * sizeof(**matrix));
matrix[i][0] = i;
}
for (unsigned i = 1; i < size; i++)
{
for (unsigned j = 1; j < i; j++)
do
matrix[i][j] = RANDOM(MIN, MAX);
while (!matrix[i][j]);
matrix[i][i] = rand() % 2 - 1;
}
return matrix;
}
int main(void)
{
int **matrix = getMatrix(EDGES + 1);
graph x;
init(&x, matrix, EDGES + 1);
add_vertex(&x, EDGES + 1);
}
At gptr->matrix[i] = realloc(gptr->matrix[i], gptr->size * sizeof(**gptr->matrix)); the program gets paused by an exception Trace/breakpoint trap. I have googled for a while, and to me it's most likely there is something wrong with my reallocation, but I have no idea what's wrong. Besides, it works fine on clang and even on online gcc 7.4 whereas fails to succeed on my gcc 8.1. Can anyone see where I'm mistaken?
On the first entry to add_vertex, gptr->size == 8 and gptr->matrix points to an array of 8 pointers to malloc'ed memory.
gptr->size++;
Now gptr->size == 9.
gptr->matrix = realloc(gptr->matrix, gptr->size * sizeof(*gptr->matrix));
And now gptr->matrix points to an array of 9 pointers. gptr->matrix[0] .. gptr->matrix[7] are the valid malloc'ed pointers from before, and gptr->matrix[8] contains uninitialized garbage.
for (unsigned i = 0; i < gptr->size; i++)
/* ERROR */
gptr->matrix[i] = realloc(gptr->matrix[i], gptr->size * sizeof(**gptr->matrix));
Since gptr->size == 9, this iterates 9 times, and on the 9th iteration, the garbage pointer gptr->matrix[8] is passed to realloc. Not good.
You could iterate the loop gptr->size - 1 times instead, and initialize gptr->matrix[gptr->size - 1] = malloc(...) separately. Or to be a little lazy and avoid code duplication, you could initialize gptr->matrix[gptr->size - 1] = NULL before this loop, keep it iterating gptr->size times, and rely on the handy feature that realloc(NULL, sz) is equivalent to malloc(sz).
I am working on a project in which I need to check neighboring cells of a specific cell in a dynamically allocated 2D char array. Basically, If certain neighboring cells are 'X' for example, then the current cell you are on becomes '-'. To allocate the 2D array, I used a single malloc call:
char *array = (char *)malloc(numRows * numCols * sizeof(char));
To access an element while using a double for loop, I use this:
for (int i = 0; i <= getNumRows(); i++)
{
for (int j = 0; j < getNumCols(); j++)
{
printf("%c ", **(array + i * getNumCols() + j));
}
printf("\n");
}
How would I access and view the neighboring cells of the current element?
The code posted to display the matrix has problems:
the outer loop should stop when i == getNumRows() and
the printf argument should use a single * dereferencing operator
Here is a modified version:
for (int i = 0; i < getNumRows(); i++) {
for (int j = 0; j < getNumCols(); j++) {
printf("%c ", *(array + i * getNumCols() + j));
}
printf("\n");
}
Which can also be rewritten to avoid recomputing the matrix sizes repeatedly:
for (int i = 0, row = getNumRows(), cols = getNumCols(); i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%c ", array[i * cols + j]);
}
printf("\n");
}
Accessing the neighbouring cells of cell r,c depends on how you deal with boundaries:
if boundaries should not be crossed, you must test if r and/or c are on a boundary to produce between 3 and 8 neighbours.
if boundaries wrap as a torus, you can just compute r+/-1 % rows and c+/-1 % cols to always produce 8 neighbours.
To simplify the first case, you can allocate the matrix with 2 extra columns and rows, with char *array = malloc(sizeof(char) * (numRows + 1) * (numCols + 2)); and use the inner space (active area) this way:
for (int i = 1; i <= getNumRows(); i++) {
for (int j = 1; j <= getNumCols(); j++) {
printf("%c ", *(array + i * getNumCols() + j));
}
printf("\n");
}
If you initalize the boundary rows and columns in the matrix as ' ', you can always access the 8 cells at r+/-1, c+/-1 and check for 'X' without special casing the boundary rows of the active part.
Accessing these neighbouring cells can be done according to the implementation choices:
int rows = getNumRows(), cols = getNumCols();
char *cellp = array + r * cols + c;
// using extra rows and columns
char top_1 = cellp[-cols - 1];
char top_2 = cellp[-cols];
char top_3 = cellp[-cols + 1];
char mid_1 = cellp[-1];
char mid_2 = cellp[+1];
char bot_1 = cellp[+cols - 1];
char bot_2 = cellp[+cols];
char bot_3 = cellp[+cols + 1];
// using torus-like wrapping
char top_1 = array[(r + rows - 1) % rows * cols + (c + cols - 1) % cols];
char top_2 = array[(r + rows - 1) % rows * cols + c];
char top_3 = array[(r + rows - 1) % rows * cols + (c + 1) % cols];
char mid_1 = array[r * cols + (c + cols - 1) % cols];
char mid_2 = array[r * cols + (c + 1)];
char bot_1 = array[(r + 1) % rows * cols + (c + cols - 1) % cols];
char bot_2 = array[(r + 1) % rows * cols + c];
char bot_3 = array[(r + 1) % rows * cols + (c + 1) % cols];
// using tests
char top_1 = (r == 0 || c == 0 ) ? 0 : cellp[-cols - 1];
char top_2 = (r == 0 ) ? 0 : cellp[-cols];
char top_3 = (r == 0 || c == cols - 1) ? 0 : cellp[-cols + 1];
char mid_1 = ( c == 0 ) ? 0 : cellp[-1];
char mid_2 = ( c == cols - 1) ? 0 : cellp[+1];
char bot_1 = (r == rows - 1 || c == 0 ) ? 0 : cellp[+cols - 1];
char bot_2 = (r == rows - 1 ) ? 0 : cellp[+cols];
char bot_3 = (r == rows - 1 || c == cols - 1) ? 0 : cellp[+cols + 1];
I would use a pointer to the array. It makes array indexing much easier. Example prints neighbouring cells.
void print_n(void *arr, size_t nrows, size_t ncols, size_t col, size_t row)
{
int (*array)[nrows][ncols] = arr;
if(col) printf("Left: %d\n", (*array)[row][col - 1]);
if(col < ncols - 1) printf("Right: %d\n", (*array)[row][col + 1]);
if(row) printf("Top: %d\n", (*array)[row - 1][col]);
if(row < nrows - 1) printf("Right: %d\n", (*array)[row + 1][col]);
}
int main(void)
{
size_t ncols = 10, nrows = 20;
int (*array)[nrows][ncols] = malloc(sizeof(*array));
for(size_t row = 0; row < nrows; row++)
for(size_t col = 0; col < ncols; col++)
(*array)[row][col] = row * 100 + col;
print_n(array, nrows, ncols, 6, 7);
free(array);
}
https://godbolt.org/z/7Yoff5
I'm currently attempting to write an algorithm for optimizing matrix multiplication over GF(2) using bit-packing. Both matrices A and B are provided in column major order so I start by copying A into row-major order and then packing the values into 8-bit integers and using parity checking to speed up operations. I need to be able to test square matrices of up to 2048x2048, however, my current implementation provides the correct answer up to 24x24 and then fails to compute the correct result. Any help would be appreciated.
//Method which packs an array of integers into 8 bits
uint8_t pack(int *toPack) {
int i;
uint8_t A;
A = 0;
for (i = 0; i < 8; i++) {
A = (A << 1) | (uint8_t)toPack[i];
}
return A;
}
//Method for doing matrix multiplication over GF(2)
void matmul_optimized(int n, int *A, int *B, int *C) {
int i, j, k;
//Copying values of A into a row major order matrix.
int *A_COPY = malloc(n * n * sizeof(int));
int copy_index = 0;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
A_COPY[copy_index] = A[i + j * n];
copy_index++;
}
}
//Size of the data data type integers will be packed into
const int portion_size = 8;
int portions = n / portion_size;
//Pointer space reserved to store packed integers in row major order
uint8_t *compressedA = malloc(n * portions * sizeof(uint8_t));
uint8_t *compressedB = malloc(n * portions * sizeof(uint8_t));
int a[portion_size];
int b[portion_size];
for (i = 0; i < n; i++) {
for (j = 0; j < portions; j++) {
for (k = 0; k < portion_size; k++) {
a[k] = A_COPY[i * n + j * portion_size + k];
b[k] = B[i * n + j * portion_size + k];
}
compressedA[i * n + j] = pack(a);
compressedB[i * n + j] = pack(b);
}
}
//Calculating final matrix using parity checking and XOR on A and B
int cij;
for (i = 0; i < n; ++i) {
for (j = 0; j < n; ++j) {
int cIndex = i + j * n;
cij = C[cIndex];
for (k = 0; k < portions; ++k) {
uint8_t temp = compressedA[k + i * n] & compressedB[k + j * n];
temp ^= temp >> 4;
temp ^= temp >> 2;
temp ^= temp >> 1;
uint8_t parity = temp & (uint8_t)1;
cij = cij ^ parity;
}
C[cIndex] = cij;
}
}
free(compressedA);
free(compressedB);
free(A_COPY);
}
I have two remarks:
you should probably initialize cij to 0 instead of cij = C[cIndex];. It seems incorrect to update the destination matrix instead of storing the result of A * B. Your code might work for small matrices by coincidence because the destination matrix C happens to be all zeroes for this size.
it is risky to compute the allocation size as malloc(n * n * sizeof(int)); because n * n might overflow with int n if int is smaller than size_t. Given the sizes you work with, it is probably not a problem here, but it is a good idea to always use the sizeof as the first operand to force conversion to size_t of the following ones:
int *A_COPY = malloc(sizeof(*A_COPY) * n * n);
I am currently implementing an N x 2 matrix of floats on the heap as follows:
float **matrix = malloc(sizeof(float*) * n_cols);
for (int i = 0; i < n_cols; ++i) {
matrix[i] = malloc(sizeof(float) * 2);
}
The elements of matrix are not contiguous in memory, making this data structure cache unfriendly (as I understand it). I am trying to re-write the above to create a genuine 2D array on the heap. Based on some previous SO posts, I tried the following:
float (*matrix)[2] = malloc(sizeof(float) * n_cols * 2);
However, this lead to a segmentation fault when I ran my code.
If you want the whole array to be contiguous then you need to declare it as follows.
float *matrix = malloc(n1 * n2 * sizeof(float));
Does this help. Note the second way the matrix has been allocated.
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
size_t r = 0;
size_t c = 0;
int rows = 82;
int columns = 30;
float *matrix = malloc(rows * columns * sizeof(float));
for(r = 0; r < rows; r++) {
printf("%zu - ", r);
for(c = 0; c < columns; c++) {
printf("%zu|", c);
matrix[r + r*c] = 1.0;
}
printf("\n");
}
float **matrix2 = malloc(rows * sizeof(float*));
for(r = 0; r < rows; r++) {
matrix2[r] = malloc(columns * sizeof(float));
}
for(r = 0; r < rows; r++) {
printf("%zu - ", r);
for(c = 0; c < columns; c++) {
printf("%zu|", c);
matrix2[r][c] = 1.0;
}
printf("\n");
}
free(matrix);
for(r = 0; r < rows; r++) {
free(matrix2[r]);
}
free(matrix2);
return 0;
}
You can find a benchmark with the code here...
https://github.com/harryjackson/doc/blob/master/c/cache_locality_2d_array_test.c
I think you want something like this.
float ** matrix = malloc(sizeof(float) * ((n_col * 2) + (n_col * sizeof(float*));
for(i = 0; i < n_col; i++)
{
matrix[i] = matrix + (n_col *sizeof(float*)) + ((i * 2) *sizeof(float));
}
The size of your matrix is 2* n_col, however the first index into your matrix is going to be a pointer to a column. You have to allocate additional space for these pointers. This is where the (n_col * sizeof(float *)) comes into play. Each row is of size (2 * sizeof(float)), so each of the first indexed in the matrix need to point to an array of memory (2 * sizeof(float)) bytes away from the last one.
It looks something like this.
m[0] m[1] m[2]
matrix matrix + 1 * (2 * sizeof(float)) matrix + 2 * (2 * sizeof(float))
The second index deference a location into the memory pointed to by m[x].