I am trying to do complex vector addition and dot product using structures in C for a project. I have my code written, however, while it is compiling without a problem, once i run my program it stops working. I have other parts to the program but this is only the relevant part. I am also trying to do matrix addition and multiplication with complex numbers. I think I can modify the others if I can get these working. Any help at all would be appreciated. Thanks, I appreciate it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define PI 3.14159265359
typedef struct complex
{
double re;
double im;
}complex;
typedef struct vect_complex
{
double *re;
double *im;
}vect_complex;
typedef struct mat_complex
{
//int i=0,j=0;
double re[100][100];
double im[100][100];
}mat_complex;
void vector_add(vect_complex a[4], vect_complex b[4], vect_complex c[4])
{
int i;
for(i=0; i<3 ;i++);
{
c->re[i] = a->re[i] + b->re[i];
c->im[i] = a->im[i] + b->im[i];
}
printf("Vector addition = (%f + %f*j)i + (%f +%f*j)j + (%f + %f*j)k\n\n",c- >re[0],c->im[0],c->re[1],c->im[1],c->re[2],c->im[2]);
}
void addmx(mat_complex *a, mat_complex *b, mat_complex *c)
{
int i, j;
for ( i = 0 ; i < '\0' ; i++ )
{
for ( j = 0 ; j < '\0' ; j++ )
{
c->re[i][j] = a->re[i][j] + b->re[i][j];
c->im[i][j] = a->im[i][j] + b->im[i][j];
}
}
printf("***Matrix Addition***\n");
for ( i = 0 ; i < '\0' ; i++ )
{
for ( j = 0 ; j < '\0' ; j++ )
{
printf("(%f + %f*j) ", c->re[i][j],c->im[i][j]);
}
printf("\n");
}
}
int main()
{
vect_complex aaa;
vect_complex bbb;
*aaa.re = 5;
*aaa.im = 4;
*bbb.re = 3;
*bbb.im = 2;
vect_complex ccc;
vector_add(&aaa, &bbb, &ccc);
vector_dot_prod(&aaa, &bbb, &ccc);
return 0;
}
There are a number of issues to deal with here.
1. vect_complex
Perhaps you'd like your vect_complex to hold a fixed number of elements, in which case it should be defined:
typedef struct vect_complex
{
double re[3];
double im[3];
} vect_complex;
Alternatively, you can keep your current definition but you will need to allocate new arrays every time you use the structure:
int main(void)
{
vect_complex vc;
vc.re = (double *) malloc(3 * sizeof(double));
vc.im = (double *) malloc(3 * sizeof(double));
vc.re[0] = 1.0;
vc.im[0] = 2.0;
...
}
2. vector_add
This function should be taking references to vect_complex as inputs, not arrays of complex vectors. This implementation assumes the definition of vect_complex I gave above.
void vector_add(vect_complex * a, vect_complex * b, vect_complex * result)
{
int i;
for (i = 0; i < 3; i++)
{
result->re[i] = a->re[i] + b->re[i];
result->im[i] = a->im[i] + b->im[i];
}
}
3. addmx
I'm not sure what the '\0's are doing here. Change it to
for (i = 0; i < 100; i++)
for (j = 0; j < 100; j++)
{
...
}
At first, your program stops at the line *aaa.re = 5;
int main()
{
vect_complex aaa;
vect_complex bbb;
*aaa.re = 5; //your program stops here.
....
}
The reason is that you defined structure aaa which allocates memory for double pointer re and im , NOT for the double values.
As of now these pointers will point to uninitialized value. when you refer like *aaa.re ie) when you dereference it, you will get segmentation fault.
For example, aaa.re points to 0x17 in my box. when i dereference it, am getting segmentation fault, since it is referring the memory address which is out of program memory area.
To resolve this problem, you should allocate the memory for double and store the address
of it into the pointer re. Then store the double value.
Brain covered Other details perfectly.
Thanks,
nvseenu
Related
typedef struct{
unsigned long a;
unsigned long b;
unsigned long c;
} mini_struct;
struct ministruct** build_2Dstruct(unsigned long x, unsigned long y){
double x_squared = pow(2, x);
struct ministruct** temp = (mini_struct**)malloc(x*sizeof(mini_struct*));
for(int i = 0; i < x_squared; i++){
temp[i] = (mini_struct*)malloc(y*sizeof(mini_struct));
for(int j = 0; j < y; j++){
temp[i][j].a = 0;
etc....
}
}
return temp;
}
In the code above I am trying to create a 2D array of ministructs**, with the whole struct being made out of 2^x ministructs*, and each ministruct* has y amount of ministructs.
aka:
x = 2,
y = 2,
[[struct, struct], [struct, struct], [struct, struct], [struct, struct]]
However, for some reason when I try to access the second element or index 1 of the struct inside each struct*, it says there is an error: "expression must be pointer to complete object".
I just do not understand why the code is not allowing me to access each individual element of the elements of the array?
Thanks
You are trying to make an x by y array of structs. So:
// create array of x pointers
mini_struct **temp = malloc(x*sizeof(mini_struct*));
for (int i=0; i<x; i++) {
// to array of y structs
temp[i] = malloc(y*sizeof(mini_struct));
for (int j=0; j < y; j++) {
temp[i][j].a = 0;
... etc.
Question is incomplete so I will be making asumptions.
You seem to be wanting to allocate a 2D array of structs and initialize all members to 0. Here is a possible solution:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
typedef struct mini_struct{
unsigned long a;
unsigned long b;
unsigned long c;
} mini_struct;
struct mini_struct** build_2Dstruct(unsigned long x, unsigned long y){
double x_squared = pow(x, 2);
mini_struct **temp = (mini_struct **) malloc(x_squared * sizeof(mini_struct*));
for(int i = 0; i < x_squared; i++){
temp[i] = (mini_struct *) calloc(y, sizeof(mini_struct));
}
return temp;
}
int main () {
int x = 3;
int y = 4;
mini_struct **struct2D = build_2Dstruct(x, y);
int x_squared = pow(x,2);
for (int i = 0; i < x_squared; ++i) {
for (int j = 0; j < y; ++j) {
printf("Value of data stored at struct[%d][%d] is: %d\n", i, j, struct2D[i][j]);
}
}
for (int i = 0; i < x_squared; ++i) {
free(struct2D[i]);
}
free(struct2D);
}
As you can see, this contains the whole program, not just the snippet you showed. In this case, a main function would have been useful so that we don't have to guess what you want to do. My solution creates the 2D array with all elements initialized to 0 (you can use calloc to do that, no need for a second for loop).
Another important point is that, because the function returns a newly heap allocated 2D array, you need to free it to avoid a memory leak (end of main function).
You allocate x pointers to mini_struct:
mini_struct **temp = (mini_struct **) malloc(x_squared * sizeof(mini_struct*));
But then when you initialize them:
for(int i = 0; i < x_squared; i++){
temp[i] = (mini_struct *) calloc(y, sizeof(mini_struct));
}
You index temp based on upto x_squared.
Consider if x is 2. You would allocate temp to be an array of two pointers to mini_struct. But then your for loop would attempt to initialize four elements in temp.
I need to allocate contiguous space for a 3D array. (EDIT:) I GUESS I SHOULD HAVE MADE THIS CLEAR IN THE FIRST PLACE but in the actual production code, I will not know the dimensions of the array until run time. I provided them as constants in my toy code below just to keep things simple. I know the potential problems of insisting on contiguous space, but I just have to have it. I have seen how to do this for a 2D array, but apparently I don't understand how to extend the pattern to 3D. When I call the function to free up the memory, free_3d_arr, I get an error:
lowest lvl
mid lvl
a.out(2248,0x7fff72d37000) malloc: *** error for object 0x7fab1a403310: pointer being freed was not allocated
Would appreciate it if anyone could tell me what the fix is. Code is here:
#include <stdio.h>
#include <stdlib.h>
int ***calloc_3d_arr(int sizes[3]){
int ***a;
int i,j;
a = calloc(sizes[0],sizeof(int**));
a[0] = calloc(sizes[0]*sizes[1],sizeof(int*));
a[0][0] = calloc(sizes[0]*sizes[1]*sizes[2],sizeof(int));
for (j=0; j<sizes[0]; j++) {
a[j] = (int**)(a[0][0]+sizes[1]*sizes[2]*j);
for (i=0; i<sizes[1]; i++) {
a[j][i] = (int*)(a[j]) + sizes[2]*i;
}
}
return a;
}
void free_3d_arr(int ***arr) {
printf("lowest lvl\n");
free(arr[0][0]);
printf("mid lvl\n");
free(arr[0]); // <--- This is a problem line, apparently.
printf("highest lvl\n");
free(arr);
}
int main() {
int ***a;
int sz[] = {5,4,3};
int i,j,k;
a = calloc_3d_arr(sz);
// do stuff with a
free_3d_arr(a);
}
Since you are using C, I would suggest that you use real multidimensional arrays:
int (*a)[sz[1]][sz[2]] = calloc(sz[0], sizeof(*a));
This allocates contiguous storage for your 3D array. Note that the sizes can be dynamic since C99. You access this array exactly as you would with your pointer arrays:
for(int i = 0; i < sz[0]; i++) {
for(int j = 0; j < sz[1]; j++) {
for(int k = 0; k < sz[2]; k++) {
a[i][j][k] = 42;
}
}
}
However, there are no pointer arrays under the hood, the indexing is done by the magic of pointer arithmetic and array-pointer-decay. And since a single calloc() was used to allocate the thing, a single free() suffices to get rid of it:
free(a); //that's it.
You can do something like this:
int ***allocateLinearMemory(int x, int y, int z)
{
int *p = (int*) malloc(x * y * z * sizeof(int));
int ***q = (int***) malloc(x * sizeof(int**));
for (int i = 0; i < x; i++)
{
q[i] = (int**) malloc(y * sizeof(int*));
for (int j = 0; j < y; j++)
{
int idx = x*j + x*y*i;
q[i][j] = &p[idx];
}
}
return q;
}
void deallocateLinearMemory(int x, int ***q)
{
free(q[0][0]);
for(int i = 0; i < x; i++)
{
free(q[i]);
}
free(q);
}
I use it and works fine.
I am playing around with pointers and structs. This is the program I have been messing with. I am getting a segfault error and I am not sure why. I have looked through it for awhile but can't seem to pinpoint the issue. Can someone explain it to me?
EDIT: in createArray I am getting a segfault at *purp[i][j] = '1';
#include <stdio.h>
#include <stdlib.h>
struct purple_struct{
int x;
int y;
char **purp;
};
void print(int x, int y){
printf("%d %d\n", x, y);
return;
}
void createArray(char*** purp, int x, int y){
int i, j;
for (i = 0; i < x; ++i){
for (j = 0; j < y; ++j){
*purp[i][j] = '1';
}
}
return;
}
int main(){
int i, j;
struct purple_struct dog;
dog.x = 3;
dog.y = 4;
dog.purp = (char **)malloc(dog.x * sizeof(char *));
for (i = 0; i < dog.x; ++i){
dog.purp[i] = (char *)malloc(dog.y * sizeof(char));
}
createArray(&dog.purp, dog.x, dog.y);
for (i = 0; i < dog.x; ++i){
for (j = 0; j < dog.y; ++j){
printf("%c", dog.purp[i][j]);
}
}
print(dog.x, dog.y);
return 0;
}
You need to understand the concept of operator precedence. Just like in mathematics, where an expression like 1 + 2 × 3 means 1 + (2 × 3) and not (1 + 2) × 3, programming languages have rules as to the order in which different operators in an expression are performed.
The rules for C are here: http://en.cppreference.com/w/c/language/operator_precedence
In your case, the problem is that *purp[i][j] actually means *(purp[i][j]), and not (*purp)[i][j] as you were expecting.
void createArray(char*** purp, int x, int y){
*purp[i][j] = '1';
I think they should be
void createArray(char** purp, int x, int y){
purp[i][j] = '1';
And in main
createArray(&dog.purp, dog.x, dog.y);
'&' is not needed here because you're already passing a pointer. '&' is usually used to pass the address of a variable.
Correcting these few things it compiles just fine, not sure about what you want to do.
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'm writing the minesweeper game in C. I want be able to play games with different minefields with different sizes and number of mines
I've created such structures to describe my data:
typedef struct t_Place Place;
struct t_Place{
unsigned numberOfMinesNear;
int mine;
int state;
};
typedef struct t_Minefield Minefield;
struct t_Minefield{
int xSize;
int ySize;
unsigned minesNumber;
Place **places;
};
So, now I'm trying to initialize my minefield. I do the following:
void makeGame(Minefield *minefield, unsigned x, unsigned y, unsigned mines){
int i, j;
minefield->places = malloc(x * y * sizeof(Place));
for(i = 0; i < x; i++)
for(j = 0; j < y; j++){
minefield->places[i][j].mine = EMPTY;
minefield->places[i][j].state = HIDDEN;
minefield->places[i][j].numberOfMinesNear = 0;
}
minefield->xSize = x;
minefield->ySize = y;
unsigned minesToPlace = mines;
srand(time(NULL));
while(minesToPlace > 0){
i = rand() % x;
j = rand() % y;
if(minefield->places[i][j].mine)
continue;
minefield->places[i][j].mine = MINE;
minesToPlace--;
}
minefield->minesNumber = mines;
// here will be call of play(minefield) function to start the game
}
int main(){
Minefield *gameField = (Minefield *) malloc(sizeof(Minefield));
makeGame(gameField, DEFAULT_X, DEFAULT_Y, DEFAULT_MINES);
// DEFAULT_X = DEFAULT_Y = DEFAULT_MINES = 10
free(gameField);
return 0;
}
I'm getting segfault at first line of code in makeGame function. What i'm doing wrong? I want allocate memory for my minefield dynamically, not statically.
minefield->places = malloc(x * y * sizeof(Place));
The above memory allocation might be the source of the problem , places is a two star pointer , so there must be two malloc() calls , one to allocate the row number **place pointers , and then another malloc() , to allocate column number of *place pointers of type place.
Here is a SSCCE of allocating/initializing a two star pointer contained inside a structure.
#include <stdio.h>
#include <stdlib.h>
#define ROW_SZ 5
#define COL_SZ 25
typedef struct demo{
char **str;
}demo;
int main()
{
demo *d = malloc( sizeof(demo) );
d->str = malloc(ROW_SZ * sizeof(char*) ); //d->str is assigned char**
for ( i = 0; i < ROW_SZ; i++ )
d->str[i] = malloc(COL_SZ * sizeof(char) ); //d-str[i] is assigned char*
// code here to use d->str[ROW_SZ][COL_SZ]
for ( i = 0; i < ROW_SZ; i++ )
free(d->str[i]);
free(d->str);
free(d);
return 0;
}
This is how I usually see 2D arrays allocated:
minefield->places = malloc(x * sizeof(Place *));
for(i = 0; i < x; i++)
{
minefield->places[i] = malloc(x * sizeof(Place));
}
Try this and see if it makes you segfault vanish.
I have this complicated structure thingie:
#include <stdlib.h>
typedef struct {
int x;
int y;
} SUB;
typedef struct {
int a;
SUB *z;
} STRUCT;
#define NUM 5
int main(void)
{
STRUCT *example;
int i;
example = malloc(sizeof(STRUCT));
example->z = malloc(NUM * sizeof(SUB));
for(i = 0; i < NUM; ++i) {
/* how do I access variable in certain struct of array of z's */
}
return 0;
}
example is dynamically allocated structure and z inside the example is dynamically allocated array of SUB structures.
How do I access certain variable in certain element of structure z?
I have been trying something like this: example->z[i].x but it doesnt seem to work.
At the moment I am using this shabby looking workaraound:
SUB *ptr = example->z;
int i;
for(i = 0; i < amount_of_z_structs; ++i) {
/* do something with 'ptr->x' and 'ptr->y' */
ptr += sizeof(SUB);
}
Your problem isn't where you say it is. Your code as posted gives a compile error:
error: request for member ‘z’ in something not a structure or union
at the line
example.z = malloc(sizeof(STRUCT));
because you meant to write example->z, since example is a pointer to STRUCT, not a STRUCT.
From there on, you can access example->z[i].x exactly as you said. That syntax has always been fine.
For example:
/* your declarations here */
example = malloc(sizeof(STRUCT));
example->z = malloc(NUM * sizeof(SUB));
for(i = 0; i < NUM; ++i) {
example->z[i].x = i;
example->z[i].y = -i;
printf("%d %d\n", example->z[i].x, example->z[i].y);
}
/* output:
0 0
1 -1
2 -2
3 -3
4 -4
*/
When you have pointers pointing to pointers you often end up running into precedence issues. I can't recall if this is one, but you might try (example->b)[i].x.
First of all, your second malloc is wrong; example is a pointer so this:
example.z = malloc(NUM * sizeof(SUB));
should be this:
example->z = malloc(NUM * sizeof(SUB));
Then in your loop you can say things like this:
example->z[i].x = i;
example->z[i].y = i;
You'll also want to have this near the top of your file:
#include <stdlib.h>
Try this:
int my_x = example[3].z[2].x;
The above code will first access the example[3] (the fourth element of the example array).
Once you get that particular element, its contents can be automatically access in the same way as you do with normal objects.
You then access z[2] from that element. Note that, example[3] is an element, so you could use a . to access its members; if its an array, you can access it as an array.
So till now, example[3].z[2] is one element of the SUB array inside one element of the example array.
Now you can simply access the member x using the way shown above.
typedef struct {
int x;
int y;
} SUB;
typedef struct {
int a;
SUB *z;
} STRUCT;
STRUCT *example;
int main() {
example = malloc(sizeof(STRUCT)*10); //array of 10;
int i=0,j=0;
for (;i<10;i++){
example[i].a = i;
example[i].z = malloc(sizeof(SUB)*5);
for (j=0; j<5; j++)
example[i].z[j].x = example[i].z[j].y = j;
}
//access example[3] and access z[2] inside it. And finally access 'x'
int my_x = example[3].z[2].x;
printf("%d",my_x);
for (i=0;i<10;i++){
printf("%d |\n",example[i].a);
//example[i].z = malloc(sizeof(SUB)*5);
for (j=0; j<5; j++)
printf("%d %d\n",example[i].z[j].x,example[i].z[j].y);
free(example[i].z);
}
free(example);
}
In the 'shabby workaround', you wrote:
SUB *ptr = example->z;
int i;
for(i = 0; i < amount_of_z_structs; ++i) {
/* do something with 'ptr->x' and 'ptr->y' */
ptr += sizeof(SUB);
}
The problem here is that C scales pointers by the size of the object pointed to, so when you add 1 to a SUB pointer, the value is advanced by sizeof(SUB). So, you simply need:
SUB *ptr = example->z;
int i;
for (i = 0; i < NUM; ++i) {
ptr->x = ptr->y = 0;
ptr++;
}
Of course, as others have said, you can also do (assuming C99):
for (int i = 0; i < NUM; ++i)
example->z[i].x = example->z[i].y = 0;
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#define NUM 5
typedef struct
{
int x;
int y;
}SUB;
typedef struct
{
int a;
SUB* z;
}STRUCT;
void main(void)
{
clrscr();
printf("Sample problem..\n\n");
STRUCT* example;
int i;
example = (STRUCT*)malloc(sizeof(STRUCT));
example->z = (SUB*)malloc(NUM * sizeof(SUB));
for(i = 0; i < NUM; i++)
{
example->z[i].x = i +1;
example->z[i].y = (example->z[i].x)+1;
printf("i = %d: x:%d y:%d\n", i, example->z[i].x, example->z[i].y);
}
}