Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
[EDIT] The main problem was that the fitness of my evolution returned the same value every time after changing some int into float values. The misterious point is that i restarted the computer and it surprisingly worked again.
I'm calling a function from my main, when i debug the code, the variables contain data, but in the header of the function, when i debug, my data is lost and the reference on memory is the same (i'm compiling with visual Studio 2013), this only happens in some of the variables (you can check which ones in the pictures below)
int main(){
float resultados[NUMCROMOSOMAS][CANTIDADMEDICIONES];
int in[CANTIDADMEDICIONES][NUMVAR];
char gramaticas[NUMCROMOSOMAS][LONGITUDCADENA];
int mejorValorIndividuo[100];
char variableNames[NUMVAR + 1];
float fitness[NUMCROMOSOMAS];
char mejorindividuo[LONGITUDCADENA];
float medicionesObtenidas[NUMCROMOSOMAS][CANTIDADMEDICIONES];
int i,j;
(Initializations, some of the relevant ones are)
for (i = 0; i < NUMCROMOSOMAS; i++)
fitness[i] = 0.0;
for (i = 0; i < CANTIDADMEDICIONES; i++)
in[i][0] = i;
Yeah, that was a bidimensional array using one column
And here is the main loop of my program
int curr = MAXINT;
i = 0;
while ( isNotGoodEnough(curr) ){
i++;
curr = generacion(poblacion, results, input, collectedData, gramaticas, mejorindividuo, variableNames, fitness);
}
return poblacion[0][0];
}
The header of my function is this:
int generacion(int poblacion[NUMCROMOSOMAS][SIZECROMOSOMAS],
float resultados[NUMCROMOSOMAS][CANTIDADMEDICIONES],
int in[CANTIDADMEDICIONES][NUMVAR],
float valoresEsperados[NUMCROMOSOMAS][CANTIDADMEDICIONES],
char gramaticas[NUMCROMOSOMAS][LONGITUDCADENA],
char * mejorIndividuo,
char variableNames[NUMVAR],
float fitness[NUMCROMOSOMAS]){
Here is the compiler before the calling
Here is the compiler right after the calling
What i'm doing wrong?
When you have an argument declaration like
int in[CANTIDADMEDICIONES][NUMVAR]
that's not really what the compiler uses, what it translates it to is
int (*in)[NUMVAR]
In other words in is a pointer and not an array.
What you're seeing in the debugger in the function is the pointer, but since the size of the data pointed to by the pointer is unknown the debugger can't show you the data directly. If you explicitly, in the debugger when in the function, check in[0] you will see that the data is correct.
In other words, it's not a problem with the code, it's how the debugger displays (or rather doesn't display) the data.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
First of all, this code is running without any issue on my linux desktop pc (x86_64) but on my Cyclone v (arm cpu/fpga), I have a segmentation fault because the value of the pointer is changing. The relevant line is the last one, during the for loop, the value of "layer->filename" is changing, it is correct during the first iteration (the address given by malloc) but it changes on the second one.
Basically, this bit of code is copying character from "buff" to "layer->filename", as you can see in the output file, the value of buff[i] is a valid character so it should not corrupt layer->filename.
If you have an idea of what could cause this issue, please let me know.
Thank you for your help.
typedef enum
{
CONV,
BN,
FC,
} layer_type;
typedef struct layer{
layer_type layer_type;
int shape[3];
char *filename;
} layer;
...
layer *layer=malloc(sizeof(layer));
char buff[30];
int i;
...
layer->filename = malloc(sizeof(char)*(n+1));
if(buff[0]=='b')
layer->layer_type=BN;
else if(buff[0]=='c')
layer->layer_type=CONV;
else
layer->layer_type=FC;
for(i=0; i<n ; i++)
*(layer->filename+i)=buff[i];
values of buff[i] and layer->name during the loop
Using this code
#include <stdio.h>
#include <stdlib.h>
typedef enum
{
CONV,
BN,
FC,
} layer_type;
typedef struct layer{
layer_type layer_type;
int shape[3];
char *filename;
} layer;
size_t test(size_t x) {
printf("%d\n", (int)x);
return x;
}
int main(void) {
layer *layer=malloc(test(sizeof(layer)));
return 0;
}
You can see that sizeof(layer) in the line
layer *layer=malloc(sizeof(layer));
is not the size of a structure but the size of a pointer.
This is because the name of variable is the same as the type name and the compiler treated layer in sizeof as the variable (pointer) name.
To avoid this and have it allocate the size of structure, you should change the name of type or variable to avoid confusion.
Dereferincing the pointer
layer *layer=malloc(sizeof(*layer));
also can solve this problem, but I think renaming is better.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
int doesn't seem to work with struct and I don't know why. I did the same thing as before and it worked but now it doesn't.
This is the main code.
int main()
{
struct elemente {
char *prod[20];
int cod[20];
int cant[20];
int pret[20];
};
struct elemente a[20];
int i,n=1,p[20];
char *val[20];
for(i=1;i<=n;i++){
puts("Numele produsului");
scanf("%s",&a[i].prod);
puts("Codul");
scanf("%i",&a[i].cod);
puts("Cantitatea");
scanf("%i",&a[i].cant);
puts("Pretul");
scanf("%i",&a[i].pret);
}
It works and I dont see it having problems.
This is where the problem is.
puts("Scrieti numele produsului");scanf("%s", &val);
for(i=1;i<=n;i++){
if(strcmp(val,a[i].prod)==0){
printf("Codul produsului: %i\n", a[i].cod);
printf("Cantitatea: %i\n", a[i].cant);
printf("Pretul: %i\n", a[i].pret);
//p[i]=a[i].cant*a[i].pret;
//printf("Valoarea totala a elementelor %i\n",p[i]);
}
}
The strcmp works fine. But it cannot find the integer numbers I have input with my scanf. It shows a strange code like "2303134". What did I do wrong?
Also as you can see I need to multiply 2 functions but CodeBlocks has problems with the * symbol. How can I fix this?
The problem is that your struct contains arrays of each element instead of a single one. This is also why the multiplication a[i].cant*a[i].pret won't compile, because you're attempting to multiply two int [20] instead of 2 int.
Since you create an array of struct elemente, you only need to input one element in each one:
struct elemente {
char prod[50];
int cod;
int cant;
int pret;
};
You would then change the scanf call to read in prod as follows to make sure you don't read more characters than the value can handle:
scanf("%49s",a[i].prod);
Also, be sure to check the return value of scanf to see whether a value was actually read in.
The strange code, in
printf("Codul produsului: %i\n", a[i].cod) case, is because you try to print the address of a[i].cod instead of the value of integer.
The easiest way to fix this is modify your struct to:
struct elemente {
char *prod[20];
int cod;
int cant;
int pret;
};
It seems there's no requirement to assign int arrays in your struct, int variables are sufficient.
After this modification,
p[i]=a[i].cant*a[i].pret;
printf("Valoarea totala a elementelor %i\n",p[i]);
should be ok to work.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
+I'm trying to pass from the main an array of CustomStruct by reference, but im doing something wrong:
I think i'm asking correctly for memory, but it doesn't seem so, because when i try to force some values, i get core dumped and i absolutely don't know why.
void readFile(OwnStruct **restaurant){
FILE *f;
int numTaules = 0;
f = fopen("hello.txt", "r");
if(f == NULL){
printf("Error at opening!\n");
exit(0);
}
fscanf(f,"%d",&numTaules);
//Asking for memory
*restaurant = (OwnStruct*)malloc(sizeof(OwnStruct) * numTaules);
//From here, at some point: Core Dumped
restaurant[0]->ocupades = 1;
restaurant[0]->disponibles = 2;
restaurant[1]->ocupades = 3;
restaurant[1]->disponibles = 4;
printf("%d\n",restaurant[0]->ocupades);
printf("%d\n",restaurant[0]->disponibles);
printf("%d\n",restaurant[1]->ocupades);
printf("%d\n",restaurant[1]->disponibles);
}
int main(){
typedef struct(){
int ocupades;
int disponibles;
}
OwnStruct *restaurant;
readFile(&restaurant);
return 0;
}
You are referencing the array wrong:
So far so good:
*restaurant = (OwnStruct*)malloc(sizeof(OwnStruct) * numTaules);
This is wrong:
restaurant[0]->ocupades = 1;
It should be:
(*restaurant)[0].ocupades = 1;
You must dereference the pointer to your pointer. That expression then points to the first element of the allocated array. The parentheses are needed, because postfix operators like EXPR[0] take precedence over unary operators like *EXPR, so *EXPR[0] is treated as *(EXPR[0]).
Suggestion: Work with a local pointer which is just Ownstruct *ptr. Then, just before returning from the function, store that pointer:
*restaurant = ptr;
Then you can just have ptr[0]->field = value type code in your function.
Your problem is that your function
void readFile(char fileName[], OwnStruct **restaurant)
expects two parameter, but you pass just one.
readFile(&restaurant);
Just write
readFile("myFile.txt", &restaurant);
or define your function as
void readFile(OwnStruct **restaurant)
The example you give should not currently compile - readFile expects a filename and a pointer to a pointer of OwnStruct. Your main is just providing the pointer.
The struct should defined somewhere at the top (before its use in main and readFile)
readFile is also reading numTauls from a file but then assuming it is at least 2 when assigning values to the allocated memory.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Please help, I need to read an input txt file into an array and print it out put somehow I keep getting error message.
#include <stdio.h>
void reading_into_array(int A[]);
#define MAXVALS 100
int
main(int argc, char *argv[]){
int numbers[100], i;
reading_into_array(numbers[MAXVALS]);
for(i = 0; i < 100; i++){
printf("%d", numbers[i]);
}
return 0;
}
/*input information*/
void
reading_into_array(int A[]){
double inp;
int n = 0;
while(scanf("%lf",&inp) == 1){
A[n++] = inp;
}
}
numbers[MAXVALS] is out-of-range and its type doesn't match with the function argument. use numbers instead.
Avoid using values of uninitialized variables having automatic storage duration, which invokes undefined behavior. Initialize numbers like int numbers[100]={0},i;
When calling a function that takes an array as a parameter, you only need to supply the name of the array, e.g. numbers. "numbers[MAXVALS]" would supply the value of the MAXVALth element of this array. This is wrong for two reasons:
the function needs an array, not an element
The array has a size MAXVAL; its elements are counted from zero to MAXVAL-1, so the MAXVALth element does not even exist
If you want floating point numbers in your array, declare the array as double A[MAXVAL] everywhere.
Last note: the reading_into_array function should have a check that it will prevent it from putting more than MAXVAL numbers into the array, or you risk that it will corrupt memory and crash your program.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
How do I dynamically create an array of struct in a function in C?
The struct:
typedef struct Track {
char artist[LONGSTR];
char file[LONGSTR];
int id;
int isAlbum;
char name[LONGSTR];
int pos;
char title[LONGSTR];
int time;
} Track;
The function:
int
processplaylist (struct Track** tracks, char* resp)
{
//count the tracks to return
//allocate space for the resulting tracks
*tracks = mem_alloc (count * sizeof (struct Track));
//process each track
return count;
}
And the usage:
char playliststr[] = "file: some-mp3\nTitle: Dire Straits - Romeo And Juliet\nName: TheRadio\nPos: 0\nId: 12\nOK\n"
struct Track* tracks = NULL;
int count = mpd_processplaylist(&tracks, playliststr);
Within the function the tracks are nicely processed and upto the return statement tracks points to the right location to get to the tracks. Most questions I have seen are about arrays to values, not structs.
This answer returns an array of structs, but I would like to return the count (question of style) and return the array through the parameter.
What is going wrong? After the function returns, count has the right value and tracks is still NULL.
As the not so nice people pointed out by down voting the question, the question is too broad and vague. I apologize for that, I was desperate.
As the nice people in the comments confirmed, the code is correct. Even though the debugger showed that just before the return statement everything was OK and after returning to the usage it was not.
By commenting out code lines and logging a lot, there are two things to note.
Within the function, you must refer to the individual tracks as (*tracks + i) or, for example, (*(*tracks + i)).file. Indeed, not shown in the sample code. I had tried *(tracks + i), &tracks[i] and tracks + i, which in the debugger all seemed to work and did not cause immediate errors. I guess the code messed up memory that only came out after the return.
Outside the function, in the usage, you refer to the tracks as an array, as tracks[i] or, for example, tracks[i].file.
I hope that at least my answer helps.