The program should create strings depending on input. we want to add these strings to a list, which is passed to the function as a pointer (to other char * pointers).
the code looks like this:
void main(void) {
//set angles alpha (small) & beta (large)
char ** configurations = calloc(0, sizeof(char*));
int multiplicity = 0;
createConfigString(4, 4, 0, configurations, 0, &multiplicity);
}
void createConfigString(int a, int b, int c, char ** configurations, int start, int * multiplicity) {
int x, i;
int strSize = 2 * (a + b + c);
for(x = a; x >= (a + (a % 2)) / 2; x--) {
//new entry to configurations if starting a new line
if(start == 0) {
configurations = realloc(configurations, (*multiplicity + 1) * sizeof(char *));
configurations[*multiplicity] = calloc(strSize, sizeof(char));
}
for(i = 0; i < x; i++) {
configurations[*multiplicity][start] = "a,";
}
if(b == 2) {
*multiplicity++;
configurations[*multiplicity][start + 2 * x] = "b,b\n";
start = 0;
continue;
}
configurations[*multiplicity][start + 2 * x] = "b,b,";
createConfigString(a - x, b - 2, c, configurations, start + 2 * x + 4, multiplicity);
}
}
but at compile it tells us it's trying to cast pointer into int on the lines
configurations[*multiplicity][start] = "a,";
configurations[*multiplicity][start + 2 * x] = "b,b\n";
configurations[*multiplicity][start + 2 * x] = "b,b,";
when we write
configurations[*multiplicity][start] = (int) "a,";
etc. it does compile without any warning
what are we doing wrong? thanks
Well, since configurations is a char **, then configurations[n] is a char *, and configurations[n][m] is then expected to be a char. You are attempting to assign a char * to a char, and in order to do that, the compiler has to convert the pointer to an integral type, which will then get truncated down to char size. This is generally not at all what the coder wants, so it generates the warning to let you know you're probably doing something wrong. Putting the cast in tells the compiler "yes, I really want to do this, so don't warn me". However, it probably still doesn't do what you are thinking it does...
Also, this:
char ** configurations = calloc(0, sizeof(char*));
is potentially problematic. The man page for calloc on Linux has this to say:
If nmemb or size is 0, then calloc() returns either NULL, or
a unique pointer value that can later be successfully passed to free().
Since you don't check the return value, you are potentially passing a NULL pointer into createConfigString. Perhaps your current platform actually returns a "usable" value, but it's not going to be portable. In the case it does return a NULL, it's possible that the later realloc may have problems (although on Linux, it seems it would be ok), which you also don't check for...
You can't copy strings using =, you have to use a function - such as the standard strcpy function.
So:
configurations[*multiplicity][start] = "a,";
should be:
strcpy(configurations[*multiplicity][start], "a,");
And the same type of patterns elsewhere.
Related
I dynamically allocated memory for 3D array of pointers. My question is how many pointers do I have? I mean, do I have X·Y number of pointers pointing to an array of double or X·Y·Z pointers pointing to a double element or is there another variant?
double*** arr;
arr = (double***)calloc(X, sizeof(double));
for (int i = 0; i < X; ++i) {
*(arr + i) = (double**)calloc(Y, sizeof(double));
for (int k = 0; k < Y; ++k) {
*(*(arr+i) + k) = (double*)calloc(Z, sizeof(double));
}
}
The code you apparently intended to write would start:
double ***arr = calloc(X, sizeof *arr);
Notes:
Here we define one pointer, arr, and set it to point to memory provided by calloc.
Using sizeof (double) with this is wrong; arr is going to point to things of type double **, so we want the size of that. The sizeof operator accepts either types in parentheses or objects. So we can write sizeof *arr to mean “the size of a thing that arr will point to”. This always gets the right size for whatever arr points to; we never have to figure out the type.
There is no need to use calloc if we are going to assign values to all of the elements. We can use just double ***arr = malloc(X * sizeof *arr);.
In C, there is no need to cast the return value of calloc or malloc. Its type is void *, and the compiler will automatically convert that to whatever pointer type we assign it to. If the compiler complains, you are probably using a C++ compiler, not a C compiler, and the rules are different.
You should check the return value from calloc or malloc in case not enough memory was available. For brevity, I omit showing the code for that.
Then the code would continue:
for (ptrdiff_t i = 0; i < X; ++i)
{
arr[i] = calloc(Y, sizeof *arr[i]);
…
}
Notes:
Here we assign values to the X pointers that arr points to.
ptrdiff_t is defined in stddef.h. You should generally use it for array indices, unless there is a reason to use another type.
arr[i] is equivalent to *(arr + i) but is generally easier for humans to read and think about.
As before sizeof *arr[i] automatically gives us the right size for the pointer we are setting, arr[i].
Finally, the … in there is:
for (ptrdiff_t k = 0; k < Y; ++k)
arr[i][k] = calloc(Z, sizeof *arr[i][k]);
Notes:
Here we assign values to the Y pointers that arr[i] points to, and this loop is inside the loop on i that executes X times, so this code assigns XY pointers in total.
So the answer to your question is we have 1 + X + XY pointers.
Nobody producing good commercial code uses this. Using pointers-to-pointers-to-pointers is bad for the hardware (meaning inefficient in performance) because the processor generally cannot predict where a pointer points to until it fetches it. Accessing some member of your array, arr[i][j][k], requires loading three pointers from memory.
In most C implementations, you can simply allocate a three-dimensional array:
double (*arr)[Y][Z] = calloc(X, sizeof *arr);
With this, when you access arr[i][j][k], the compiler will calculate the address (as, in effect, arr + (i*Y + j)*Z + k). Although that involves several multiplications and additions, they are fairly simple for modern processors and are likely as fast or faster than fetching pointers from memory and they leave the processor’s load-store unit free to fetch the actual array data. Also, when you are using the same i and/or j repeatedly, the compiler likely generates code that keeps i*Y and/or (i*Y + j)*Z around for multiple uses without recalculating them.
Well, short answer is: it is not known.
As a classic example, keep in mind the main() prototype
int main( int argc, char** argv);
argc keeps the number of pointers. Without it we do not know how many they are. The system builds the array argv, gently updates argc with the value and then launches the program.
Back to your array
double*** arr;
All you know is that
arr is a pointer.
*arr is double**, also a pointer
**arr is double*, also a pointer
***arr is a double.
What you will get in code depends on how you build this. A common way if you need an array of arrays and things like that is to mimic the system and use a few unsigned and wrap them all with the pointers into a struct like
typedef struct
{
int n_planes;
int n_rows;
int n_columns;
double*** array;
} Cube;
A CSV file for example is char ** **, a sheet workbook is char ** ** ** and it is a bit scary, but works. For each ** a counter is needed, as said above about main()
A C example
The code below uses arr, declared as double***, to
store a pointer to a pointer to a pointer to a double
prints the value using the 3 pointers
then uses arr again to build a cube of X*Y*Z doubles, using a bit of math to set values to 9XY9.Z9
the program uses 2, 3 and 4 for a total of 24 values
lists the full array
list the first and the very last element, arr[0][0][0] and arr[X-1][Y-1][Z-1]
frees the whole thing in reverse order
The code
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int n_planes;
int n_rows;
int n_columns;
double*** array;
} Cube;
int print_array(double***, int, int, int);
int main(void)
{
double sample = 20.21;
double* pDouble = &sample;
double** ppDouble = &pDouble;
double*** arr = &ppDouble;
printf("***arr is %.2ff\n", ***arr);
printf("original double is %.2ff\n", sample);
printf("*pDouble is %.2ff\n", *pDouble);
printf("**ppDouble is %.2ff\n", **ppDouble);
// but we can build a cube of XxYxZ doubles for arr
int X = 2;
int Y = 3;
int Z = 4; // 24 elements
arr = (double***)malloc(X * sizeof(double**));
// now each arr[i] must point to an array of double**
for (int i = 0; i < X; i += 1)
{
arr[i] = (double**)malloc(Y * sizeof(double*));
for (int j = 0; j < Y; j += 1)
{
arr[i][j] = (double*)malloc(Z * sizeof(double));
for (int k = 0; k < Z; k += 1)
{
arr[i][j][k] = (100. * i) + (10. * j) + (.1 * k) + 9009.09;
}
}
}
print_array(arr, X, Y, Z);
printf("\n\
Test: first element is arr[%d][%d[%d] = %6.2f (9XY9.Z9)\n\
last element is arr[%d][%d[%d] = %6.2f (9XY9.Z9)\n",
0, 0, 0, arr[0][0][0],
(X-1), (Y-1), (Z-1), arr[X-1][Y-1][Z-1]
);
// now to free this monster
for (int x = 0; x < X; x += 1)
{
for (int y = 0; y < Y; y += 1)
{
free(arr[x][y]); // the Z rows
}
free(arr[x]); // the plane Y
}
free(arr); // the initial pointer;
return 0;
}; // main()
int print_array(double*** block, int I, int J, int K)
{
for (int a = 0; a < I; a += 1)
{
printf("\nPlane %d\n\n", a);
for (int b = 0; b < J; b += 1)
{
for (int c = 0; c < K; c += 1)
{
printf("%6.2f ", block[a][b][c]);
}
printf("\n");
}
}
return 0;
}; // print_array()
The output
***arr is 20.21f
original double is 20.21f
*pDouble is 20.21f
**ppDouble is 20.21f
Plane 0
9009.09 9009.19 9009.29 9009.39
9019.09 9019.19 9019.29 9019.39
9029.09 9029.19 9029.29 9029.39
Plane 1
9109.09 9109.19 9109.29 9109.39
9119.09 9119.19 9119.29 9119.39
9129.09 9129.19 9129.29 9129.39
Test: first element is arr[0][0[0] = 9009.09 (9XY9.Z9)
last element is arr[1][2[3] = 9129.39 (9XY9.Z9)
Im using this method
void * col_check(void * params) {
parameters * data = (parameters *) params;
int startRow = data->row;
int startCol = data->col;
int *colm = malloc(9);
for (int i = startCol; i < 9; ++i) {
int col[10] = {0};
for (int j = startRow; j < 9; ++j) {
int val = data->arr1[j][i];
if (col[val] != 0) {
colm[i]=i;
}
else{
col[val] = 1;
}
}
}
return colm;
}
i want to get the values in the colm array to the main program. So im using the below lines to do so. basically what the colm array stores are the column indexes of the arr1 which is not valid according to sudoku rules. (not important).
parameters * param10 = (parameters *) malloc(sizeof(parameters));
param10->row = 0;
param10->col = 0;
param10->arr1 = arr1;
void * cols;
pthread_create(&thread_10, NULL, col_check, (void *) param10);
pthread_join(thread_10, &cols);
printf("Calculating column validity please wait.\n");
sleep(mdelay);
int c;
int value= (int)cols[1];
i get the error "operand of type 'void' where arithmetic or pointer type is required" when i try to get the value in cols1 to the variable "value". What am i doing wrong ? any suggestions? Full code here
In (int)cols[1] the (int) part has lower precedence than the [1] part, so the compiler tries to evaluate cols[1] first.
Then the compiler cannot calculate cols[1] because void* does not point to an item of a known size. If the compiler does not know how large cols[0] is, then how can it figure out where cols[1] is?
I am not sure what you are trying to do, but what you probably want is int value = ((int*)cols)[1];
#Mike Nakis already provided a good answer, I will fix one of your syntax errors.
When you are declaring colm as a pointer of integers column matrix you are doing it wrong. malloc is defined as:
void* malloc( size_t size );
You only allocates 9 consecutive bytes, if you want 9 consecutive bytes of ints, you would have to do either:
int *colm = malloc(sizeof(int)*9);
or:
int *colm = calloc(9, sizeof(int));
The latter is more preferable, in my point of view. But either do the same thing, except that calloc also initializes all bytes in the allocated storage to zero.
I have this code:
int * generate_code(int *bits, int Fs, int size, int *signal_size, float frameRate)
{
int sign_prev, i;
int bit, t, j=0;
int *x;
float F0, N, t0, prev_i, F1;
int temp = 0, temp1, temp2;
F0 = frameRate * BITS_PER_FRAME; // Frequency of a train of '0's = 2.4kHz
F1 = 2*F0; // Frequency of a train of '1's = 4.8kHz
N = 2*(float)Fs/F1; // number of samples in one bit
sign_prev = -1;
prev_i = 0;
x = (int *)malloc(sizeof(int));
for( i = 0 ; i < size ; i++)
{
t0 = (i + 1)*N;
bit = bits[i];
if( bit == 1 )
{
temp1 = (int)round(t0-N/2)-(int)round(prev_i+1)+1;
temp2 = (int)round(t0)-(int)round(t0-N/2+1)+1;
temp =j + temp1 + temp2;
//printf("%d\n", (int)temp);
x = realloc(x, sizeof(int)*temp); // 1
for(t=(int)round(prev_i+1); t<=(int)round(t0-N/2); t++)
{
*(x + j) = -sign_prev;
j++;
}
prev_i = t0-N/2;
for(t=(int)round(prev_i+1); t <= (int)round(t0); t++)
{
*(x + j) = sign_prev;
j++;
}
}
else
{
// '0' has single transition and changes sign
temp =j + (int)round(t0)-(int)round(prev_i);
//printf("%d\n",(int)temp);
x = realloc(x, sizeof(int)*(int)temp); // 2
for(t=(int)round(prev_i); t < (int)round(t0); t++)
{
*(x + j) = -sign_prev;
j++;
}
sign_prev = -sign_prev;
}
prev_i = t0;
}
*signal_size = j;
return x;
}
Both realloc lines, marked with //1 and //2 on the previous code, give me this error message:
assigning to int * from incompatible type void *
Because I don't want this code behaving weirdly or crashing on me, obviously, I ask will: I have some problem in the future if I simply cast it to int * by doing
x = (int*)realloc(x, sizeof(int)*(int)temp);
Thanks
In C, a value of type void* (such as the value returned by realloc) may be assigned to a variable of type int*, or any other object pointer type. The value is implicitly converted.
The most likely explanation for the error message is that you're compiling the code as C++ rather than as C. Make sure the source file name ends in .c, not .C or .cpp, and make sure your compiler is configured to compile as C rather than as C++.
(Casting the result of realloc or malloc is considered poor style in C. In C++, the cast is necessary, but you normally wouldn't use realloc or malloc in C++ in the first place.)
This should work in C. Are you perhaps using a C++ compiler to compile this? For example, some big company based in Redmond refuses to properly support a contemporary C implementation. Their compiler is C++ by default and needs some option to whack it into a C compiler.
You have stdlib.h included? Then you don't need the casts. In fact, it is best practice to not cast the malloc return.
All alloc-style functions in C return memory addresses with the most strict alignment, so the cast can't give a pointer that isn't a valid int pointer.
I want to create a bidimensional array like so:
void **mdeclaraMatrice(int nrLini,int nrColoane, int sizeOfElement)
{
int i;
void **m = malloc(nrLini * 4);
if(m==NULL)
return NULL;
for(i=0; i<nrLini; i++)
{
*(m + (i*4)) = malloc(nrColoane * sizeOfElement);
if(*(m + (i*4)) == NULL)
return NULL;
}
return m;
}
I whant to use it like this:
int **m = (int **)mdeclaraMatrice(n,m,sizeof(int));
but it doesn't work. What do I do wrong?
You should use m[i] instead of *(m+i*4) and let the compiler do the arithmetic.
In addition, you should deallocate the already-allocated memory in case of a failure.
Try this instead:
void **mdeclaraMatrice(int nrLini, int nrColoane, int sizeOfElement)
{
int i;
void **m = malloc(nrLini * sizeof(void*));
if (m == NULL)
return NULL;
for (i=0; i<nrLini; i++)
{
m[i] = malloc(nrColoane * sizeOfElement);
if (m[i] == NULL)
{
while (i-- > 0)
free(m[i]);
free(m);
return NULL;
}
}
return m;
}
[not an answer to the question, but to the indented usage of the proper answer as given by others]
To access the void pointer array as an array of int, doing this
int **m = (int **)mdeclaraMatrice(n,m,sizeof(int));
is not correct, as per the C-Standard only void* converts to any other pointer properly, void** doesn't necessarily. So it shall correctly be
void ** ppv = mdeclaraMatrice(n,m,sizeof(int));
int * pi = *ppv; /* Please note, there is NO casting necessary here! */
Then access the members like so:
pi[0] = 42
pi[1] = 43;
...
Which essently is the same as doing
*((int *) (pi + 0)) = 42;
*((int *) (pi + 1)) = 43;
which indeed does not make sense really as pi already is int*, so the fully correct approach (also taking into account the 2nd dimension) would be:
((int *)(ppv[0]))[0] = 42;
((int *)(ppv[0]))[1] = 43;
Which could be made usable by definging a macro:
#define GENERIC_ARRAY_ELEMENT(type, address, r, c) \
((type *)(address[r]))[c]
GENERIC_ARRAY_ELEMENT(int, ppv, 0, 0) = 42;
GENERIC_ARRAY_ELEMENT(int, ppv, 0, 1) = 43;
I will address the problem of allocation an array of void pointers and then interpreting them as an array of int pointers.
int **nope = (int **)mdeclaraMatrice(n,m,sizeof(int));
Even assuming the allocation was completely correct the assignment and later usage of nope is undefined behavior. void** and int** have incompatible types.
What you can do is the following. Assign the void pointers one by one to an array of int pointers.
void** arrp = mdeclaraMatrice(n,m,sizeof(int));
int* arr[n] ;
for( size_t i = 0 , i < n ; i++ )
arr[i] = arrp[i] ;
And then use the arr array, When you want to free the memory you free the original pointer:
free( arrp ) ;
The problem occurs in this line:
*(m + (i*4)) = malloc(nrColoane * sizeOfElement);
You have to know that when adding a number to an address, the address will be incremented by the number times the size of the object the address points to. So if your pointer points to an object that is of size 4 bytes, and you add 1 to it, then the address will automatically be incremented by 4, not by 1. So you should abandon *4.
Also, use the sizeof operator when allocating space, because addresses (and thus pointers) can have different sizes on different processor architectures.
Actually, you don't even need your generic 2D array function if you know the powerfull VLA features of C99. To allocate a true 2D array (no index array required), you just do this:
int (*twoDIntArray)[width] = malloc(height*sizeof(*twoDIntArray));
That's it. Accesses are just as simple:
twoDIntArray[line][column] = 42;
In this code, twoDIntArray is a pointer to an array of width integers. The malloc() call simply allocates enough space for height such line arrays. When you do the pointer arithmetic twoDIntArray[line], you add the size of line line arrays to the pointer, which produces the address of the corresponding line array. This line array is then indexed by the second array subscript [column].
Needless to say that freeing such an array is just as trivial:
free(twoDIntArray);
I have been stuck on this for a while and nothing seems to work.
I have a data structure:
DATA
{
int size;
int id;
}
And I have an array of DATA structures:
myArray = (DATA *) malloc(10 * sizeof(DATA));
Then I assign some test values:
myArray[0].size = 5;
myArray[1].size = 9;
myArray[2].size = 1;
myArray[3].size = 3;
So my starting array should look like:
5,9,1,3,0,0,0,0,0,0
Then, I call qsort(myArray,10,sizeof(DATA),comp)
Where comp is:
int comp(const DATA * a, const DATA * b)
{
return a.size - b.size;
}
And trust me, I tried many things with the compare function, NOTHING seems to work. I just never get any sorting that makes any sense.
So my starting array should look like 5, 9, 1, 3, 0, 0, 0, 0, 0, 0.
No, it really won't, at least it's not guaranteed to.
If you want zeros in there, either use calloc() to zero everything out, or put them in yourself. What malloc() will give you is a block of the size required that has indeterminant content. In other words, it may well have whatever rubbish was in memory beforehand.
And, on top of that, a and b are pointers in your comp function, you should be using -> rather than . and it's good form to use the correct prototype with casting.
And a final note: please don't cast the return from malloc in C - you can get into problems if you accidentally forget to include the relevant header file and your integers aren't compatible with your pointers.
The malloc function returns a void * which will quite happily convert implicitly into any other pointer.
Here's a complete program with those fixes:
#include <stdio.h>
#include <stdlib.h>
typedef struct {int size; int id;} DATA;
int comp (const void *a, const void *b) {
return ((DATA *)a)->size - ((DATA *)b)->size;
}
int main (void) {
int i;
DATA *myArray = malloc(10 * sizeof(DATA));
myArray[0].size = 5;
myArray[1].size = 9;
myArray[2].size = 1;
myArray[3].size = 3;
for (i = 4; i < 10; i++)
myArray[i].size = 0;
qsort (myArray, 10, sizeof(DATA), comp);
for (i = 0; i < 10; i++)
printf ("%d ", myArray[i].size);
putchar ('\n');
return 0;
}
The output:
0 0 0 0 0 0 1 3 5 9