I tried this following code but it clearly didn't work:
void main3()
{
int n;
printf("Input the dimension of the array");
scanf("%d", &n);
int* testMatrix2 = malloc(sizeof(int) * n);
testMatrix2 = {512, 51, 642}; //is there a way to do this? "expected an expression" error
}
As the comment shows, is there a way to initialize an array as you would normally do without using arrays? I know it's a risky move, but it would make my life easier during testing.
The use of for cycles would not be feasible for me as I need a sort of randomness in the array.
CodePudding user response:
As @EugeneSh. stated it is not possible for any size array. If the array has a fixed size you can wrap it into the structure:
typedef struct
{
int x[10];
}wrappedArray;
void foo(void)
{
wrappedArray *wa = malloc(sizeof(*wa));
*wa = (wrappedArray){1,2,3,4,5,6,7,8,9,10};
}
CodePudding user response:
Arrays are "non-modifiable" L-values. Therefore they cannot be assigned with = operator.
However, you could memcpy from a compound literal.
memcpy(testMatrix2, (const int[]){512, 51, 642}, sizeof(int[3]));
Just ensure that n >= 3 before doing this to avoid Undefined Behavior.
CodePudding user response:
You can use compound literal:
#include <stdio.h>
int main (void) {
int* testMatrix2 = (int []){512, 51, 642};
for (int i = 0; i < 3; i) {
printf ("%d ", testMatrix2[i]);
}
printf ("\n");
return 0;
}
Output:
# ./a.out
512 51 642
Compound literals Constructs an unnamed object of specified type in-place.
In this statement of above program
int* testMatrix2 = (int []){512, 51, 642};
(int []){512, 51, 642} is a compound literal. It will create an unnamed static array of type int [3], initialise the array to the value 512, 51 and 642 and the pointer to first element of this array object will be assigned to testMatrix2.
