What's the matter with Dev-C++, or are there errors in my code about using reference variable?
#include <stdio.h>
struct P {
int x;
};
int main(int argc, char **argv){
struct P Point[5];
struct P & rPoint;
int i;
for(i=0;i<=4;i++) {
rPoint = Point[i]; // I know. I can use Point[i].x = i. But...
rPoint.x = i;
}
for(i=0;i<=4;i++) {
rPoint = Point[i];
printf("%d\n", rPoint.x);
}
system("pause");
return 0;
}
Error: 9 C:***\main.c syntax error before '&' token
C++ does not allow unassigned references, so this is your error:
struct P & rPoint;
If you want reassignment, use a pointer.
int main(int argc, char **argv){
struct P points[5];
struct P* point;
int i;
for(i=0;i<=4;i++) {
point = points + i; // or &points[i]
point->x = i;
}
// ...
C++ references don't work like that. You have to initialize the reference when you define it. So something like:
int x = 5;
int &r = x; // Initialise r to refer to x
Also, you can't "re-seat" a reference; it will always refer to the same variable. So continuing the above example:
int x = 5;
int y = 10;
int &r = x;
r = y; // This will not re-seat y; it's equivalent to x = y
Error: 9 C:*\main.c syntax error before '&' token
Besides what the others said, you are compiling it as a C file, and in C references do not exist. Give it a .cpp extension if you want to compile it as C++, or make point a pointer instead of a reference (actually, you'll have to make it a pointer anyway, since you can't reseat a reference).
Related
bool checkSubarraySum(int* nums, int numsSize, int k) {
int i, s, found = 0;
e_t buff[10000];
int n;
e_t *set[SZ] = { 0 }, *e;
put(set, &buff[n ++], 0, -1);
s = 0;
for (i = 0; i < numsSize; i ++) {
s += nums[i];
if (k) s = s % k;
e = lookup(set, s);
if (e) {
if (i - e->idx >= 2) {
found = 1;
break;
}
} else {
put(set, &buff[n ++], s, i);
}
}
return found;
}
What is e_t *set[SZ] = { 0 }, *e; doing? e_t is a user defined type but I don't think that matters. e is not a pointer that has been defined anywhere in global scope to my knowledge, and I tried something like the following:
int *array[5] = {0}, *u;
and no syntax errors were given. The first part, i.e. int *array[5] = {0} initializes all five elements of this array to 0. But what is the purpose of *u? You can't just assign an array to something else, right, it's an address, not a pointer. And u has never even been defined, so, I would expect some sort of NameError...
Thanks for any help in advance.
It is similar to typing:
int x, y;
but notice the types when typing something like:
int a, *b, **c;
/* ^ ^ ^
* int int* int**
*/
therefore
int *array[5] = {0}, *u;
/* ^ is pointer to int */
int *array[5] = {0}, *u;
Is a declaration of two int objects. The first:
int *array[5] = {0}
declares an array-of-pointers to int [5] (meaning an array of 5 pointers to int) initialized to NULL by virtue of using the "universal initializer" {0}. The equivalent, but more intuitive initialization would be:
int *array[5] = {NULL}
The ',' is simply a separator here that allows the second declaration *u to be included in the same line without a separate int *u; declaration.
(not to be confused with the comma-operator that simply discards expressions to the left of the final ',' evaluating the last expression. See What does the comma operator , do? -- thank you #AnttiHaapala)
So:
..., *u;
declares a single (uninitialized) pointer-to int.
e_t *set[SZ] = { 0 }, *e;
is a declaration of two objects; set is an array of pointers to e_t, while e is a pointer to a single e_t. It may also be written as:
e_t *set[SZ] = {0};
e_t *e;
e_t *set[SZ] = { 0 }, *e; should be read as "the programmer hereby declares that the following are of type e_t: the objects pointed to by each SZ elements in set; and the object pointed to by e."
= {0} causes each element in set to be initialized to null pointers - the first explicitly and the remaining implicitly.
I'm working on a C assignment for school and the assignment asks us to use this specific function signature that is causing errors for my compiler.
I'm getting an error from line 38 (the smallest function signature) in vector_test.c, the error reads ""," expected (got "*")". This is my first time working in C so I think I must be doing something wrong in regards to how I have setup the typedef in types.h or something along those lines, just not exactly sure and thought I'd get some extra opinions. Anything you could point out that I'm doing wrong here would be helpful, thank you!
Here's the code:
vector_test.c
#include "types.h"
int smallest(const Vector3t, int);
void main (int argc, char *argv[]) {
unsigned int N = 0;
printf ("Number of elements ===>");
scanf ("%u", &N);
struct Vector3t points[N];
for (int i = 0; i < N; i++)
{
scanf("%d,%d,%d", &points[i].x, &points[i].y, &points[i].z);
}
for (int p = 0; p < N; p++)
{
printf("%i", points[p].x);
printf("%i", points[p].y);
printf("%i\n\n", points[p].z);
}
int result = smallest(points, N);
printf("%s", "The point closest to the origin is (");
printf("%i", points[result].x);
printf("%s", ", ");
printf("%i", points[result].y);
printf("%s", ", ");
printf("%i", points[result].z);
printf("%s", ")");
}
int smallest(const Vector3t* pts, int n)
{
int shortest = 99999999;
int shortIndex = -1;
for (int i = 0; i < n; i++)
{
int distance = pts[i].x + pts[i].y + pts[i].z;
if (distance < shortest)
{
shortest = distance;
shortIndex = i;
}
}
return shortIndex;
}
types.h
#ifndef types_H
#define types_H
struct vec3 {
int x;
int y;
int z;
};
typedef struct Vector3t {
int x;
int y;
int z;
} vec3;
#endif
Here's the assignment instructions for this specific part so you can see what I'm trying to do:
1. Create a header file called “types.h” (with a macro guard)
a. In this header file, create a struct type called vec3 with int types: x, y, and z
b. Create a typedef to the struct vec3 above and call it Vector3t
2. Create a C source file called “vector_test.c”
a. This file should include “types.h” and any other C system includes you may need
b. Create a main function that does the following:
i. Prompts the user “Number of elements ===> “
ii. Read an unsigned int from the user – this variable will be referred to as N
iii. Create an array of Vector3t of size N and call it points
iv. Read in triples of int (comma separated) from the user to populate the entire array
v. Using the function signature: int smallest(const Vector3t* pts, int n), implement a
function that returns the index of the point that is the closest to the point (0, 0, 0)
vi. Call this function and store the index into an int called result
vii. Print out to the user “The point closest to the origin is (<x>, <y>, <z>)” where <x>, <y>, and <z>
correspond to the values of points[result]
viii. Free all allocated data
Your function forward declaration is:
int smallest(const Vector3t, int);
While your function definition says:
int smallest(const Vector3t* pts, int n)
In your forward declaration you're saying that you're passing in the struct as a parameter, while in your definition you're saying that it's taking a pointer to the struct. These are incompatible signatures.
You get it wrong in the first steps:
Create a header file called "types.h" (with a macro guard)
In this header file, create a struct type called vec3 with int types: x, y, and z
Create a typedef to the struct vec3 above and call it Vector3t
For first,
struct vec3 {
int x;
int y;
int z;
};
is correct. Then to define the typedef, you first give the the actual type, then the type alias:
typedef struct vec3 Vector3t;
Alternatively, these 2 can be combined into one typedef:
typedef struct vec3 {
int x;
int y;
int z;
} Vector3t;
Also the declaration of smallest doesn't match the definition (shouldn't they look alike?) and the return type of main must be int.
I'm getting a segfault, and when I debug it I get the following message:
Cannot access memory at 0x806d128
I attempted to set a watchpoint there to monitor the address, but the response gdb gave me was:
Cannot watch constant value '0x806d128'
However when I print the pointer containing the address it recognises the struct that I've got stored there:
(body *) 0x806d128
According to gdb the error occurs in addForce(), which is a bit odd since that address is accessed earlier in init()
Here's the relevant code:
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define prec float
prec gdt = 0.0001;
typedef struct {
float Fx, Fy, vx, vy, mass;
int posX, posY;
} body;
void addForce(body* a, body* b){
int xa=(*a).posX, ya=(*a).posY;
int xb=(*b).posX, yb=(*b).posY;
float F=(*a).mass * (*b).mass * gdt /(pow(xa-xb, 2)+pow(ya-yb, 2));
float v=atan((ya-yb)/(xa-xb));
float Fx=cos(v)/F, Fy=sin(v)/F;
(*a).Fx+=Fx;
(*a).Fy+=Fy;
(*b).Fx-=Fx;
(*b).Fy-=Fy;
}
int newRandInt(int bot, int top){
return bot + (rand() % (top++));
}
prec newRand()
{
prec r = (prec)((double)rand()/(double)RAND_MAX);
return r;
}
void init(int N, body* star){
for(int i=0; i<N;i++){
star[i].posX = newRandInt(0, 800);
star[i].posY = newRandInt(0, 800);
star[i].Fx = newRand();
star[i].Fy = newRand();
star[i].vx = newRand();
star[i].vy = newRand();
star[i].mass = newRand();
}
}
int main(int argc, char* argv[]) {
int N = 200;
body* stars = malloc(sizeof(body)*N);
init(N, stars);
for(int j1=0; j1<N; j1++){
for(int j2=0; j2<N-1; j2++){
if(j1!=j2){
addForce(stars+sizeof(body)*j1, stars+sizeof(body)*j2);
}
}
}
return 0;
}
This call to addForce is not what you want:
addForce(stars+sizeof(body)*j1, stars+sizeof(body)*j2);
You don't want the sizeof(body) expression in this call to addForce. The call you probably want is:
addForce(stars+j1, stars+j2);
stars is an array of body so you can reference individual stars with
body *p = &stars[i]
or just
body *p = stars + i
Both of these have the type body*
In this line:
addForce(stars+sizeof(body)*j1, stars+sizeof(body)*j2);
when you do sizeof(body) it evaluates to size of structure in bytes, then it is multiplied by j1. So you have some_nr*j1.
That value is added to stars, which is pointer to body.
Pointer arithmetics evaluate some_nr*j1*sizeof(pointer to body).
What you want to do is stars+j1 alone, which will be correctly evaluated as pointer to body and added to arrays.
The same happends in the second part of addForce.
What you missed is that with pointers arithmetics the second operand of '+' operator is recalculated to match size of pointee.
I am trying to access my struct points. The structs memory are dynamically located. I am getting a segmentation fault that I can't figure out. My struct definitions from my .h file are as follows:
struct point{
double x;
double y;
};
struct figure{
char name[128];
int draw;
struct point *points;
};
extern struct figure *figures;
In my .c file I have:
struct figure *figures;
//initializing 10 figures
figures = malloc(10 * sizeof(struct figure));
//left the obvious NULL checking out for brevity
//I'm fairly sure this portion works for initializing 10 points for each figure
int i;
for(i = 0;i<10;i++){
figures[i].points = malloc(10 * sizeof(struct point));
//left out NULL checking again
}
Unless a problem was detected before this point this is where I am having trouble, actually storing values into points.
NOTE: index could be any int >= 0, just using a general term for simplicity
figures[index].points[index]->x = 10;
figures[index].points[index]->y = 15;
Any help with his problem would be fantastic. Thanks in advance.
figures[index].points is an array of structures, which means that indexing it (i.e. figures[index].points[index]) gives you a structure. The last two lines should be:
figures[index].points[index].x = 10;
figures[index].points[index].y = 15;
I'm surprised the compiler wouldn't catch this.
Apart from the fact that you are accessing the inner structure incorrectly,I don't see any problem in this code.
Online Demo of your code sample that works.
#include<string.h>
#include<stdio.h>
struct point{
double x;
double y;
};
struct figure{
char name[128];
int draw;
struct point *points;
};
int main()
{
struct figure *figures;
figures = malloc(10 * sizeof(struct figure));
int i = 0;
for(i = 0;i<10;i++)
{
figures[i].points = malloc(10 * sizeof(struct point));
figures[i].draw = i;
}
i = 0;
for(i = 0;i<10;i++)
{
printf("\nfigures[%d].draw = [%d]",i,figures[i].draw);
int j;
for(j = 0;j<10;j++)
{
figures[i].points[j].x = i;
figures[i].points[j].y = j;
printf("\nfigures[%d].points[%d].x = [%f]",i,j,figures[i].points[j].x);
printf("\nfigures[%d].points[%d].y = [%f]",i,j,figures[i].points[j].y);
}
}
return 0;
}
Output:
figures[0].draw = [0]
figures[0].points[0].x = [0.000000]
figures[0].points[0].y = [0.000000]
figures[0].points[1].x = [0.000000]
figures[0].points[1].y = [1.000000]
figures[0].points[2].x = [0.000000]
...so on
I don't know which direction to go,perhaps something like reflection will help?
If you're using Clang 8 or newer, you can now use the built-in compiler function __builtin_dump_struct to dump a struct. It uses the information that's naturally available at compile time to generate code that pretty-prints a struct.
Example code demonstrating the function:
dumpstruct.c:
#include <stdio.h>
struct nested {
int aa;
};
struct dumpme {
int a;
int b;
struct nested n;
};
int main(void) {
struct nested n;
n.aa = 12;
struct dumpme d;
d.a = 1;
d.b = 2;
d.n = n;
__builtin_dump_struct(&d, &printf);
return 0;
}
Example compile-and-run:
$ clang dumpstruct.c -o dumpstruct
$ ./dumpstruct
struct dumpme {
int a : 1
int b : 2
struct nested n : struct nested {
int aa : 12
}
}
If you're not using Clang >= 8 but you are using GCC, it's pretty easy to switch. Just install the clang-8 or clang-9 package and replace invocations of gcc with clang.
The answer of #Kerrek SB works realy well, I just post how to use it in a function using a void pointer.
int dump(void *myStruct, long size)
{
unsigned int i;
const unsigned char * const px = (unsigned char*)myStruct;
for (i = 0; i < size; ++i) {
if( i % (sizeof(int) * 8) == 0){
printf("\n%08X ", i);
}
else if( i % 4 == 0){
printf(" ");
}
printf("%02X", px[i]);
}
printf("\n\n");
return 0;
}
int main(int argc, char const *argv[])
{
OneStruct data1, data2;
dump(&data1, sizeof(OneStruct));
dump(&data2, sizeof(OneStruct));
return 0;
}
Here's a hex dump, about as general as you can get:
struct Foo x;
unsigned int i;
const unsigned char * const px = (unsigned char*)&x;
for (i = 0; i < sizeof(x); ++i) printf("%02X ", px[i]);
Note that the result of this is entirely implementation-defined; presumably there'll be plenty of padding, and you won't know what any of the printed values mean. (Most of them will probably just be pointers to some other part of space.)
As Etienne says, C is a statically typed language and does not have reflection, so you have to know the declaration of Foo in order to interpret the content of x.
What do you want to do with your file once you've got it? If it's going to be read back in at a later time just use fread and fwrite, like
struct foo * bar;
fwrite(bar,sizeof(*bar),1,stdout);
...
fread(bar,sizeof(*bar),1,stdin);
This will give binary output that's dependant on your compiler/platform, as long as those are unchanged you should be fine. From there you can also feed the file into a hex reader etc., though you'll need to know the layout of the struct to do anything useful with it.