Reading into array [closed] - c

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.

Related

What could cause this pointer to be corrupted? [closed]

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.

Int doesn't work in struct [closed]

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.

Passing Struct * by reference C [closed]

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.

Some data disapears from pointer when calling a function [closed]

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.

Error when passing a 2-dim array as function's parameter in C [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I try to pass a two dimensional array as a parameter to a function like this:
void comb(int n, int array[n][n-1])
{
.....
}
And in the main function:
int main(int argc, const char * argv[])
{
const int p = 10;
int array[p][p-1];
comb(p, array); //Error:No matching function for call to 'comb'
return 0;
}
The "comb" function is declared above the main function. But Xcode gives me the error message on line "comb(p, array)" that "No matching function for call to 'comb' ".
I don't know how I could fix this. Also, is there some better way to pass a 2-dim array as parameter?
Your code is correct in C99.
If you get a compiler error, it could be because you are not showing the real code, or you are not invoking your compiler in C99 mode.
In C11 it is optional whether the compiler supports VLA, but your compiler documentation should indicate whether or not it is supported.
There is no other way to pass a VLA as parameter.
If your array dimension is known at compile-time then you can replace const int p = 10; with #define ARRAY_DIM 10 ; then your array will no longer be a VLA and the function can simply be:
void comb(int array[ARRAY_DIM][ARRAY_DIM-1])
{
Never passed a matrix, but when you pass arrays, the name is just the pointer to the first element.
char myArray[10];
where myArray is really a char pointer rather than a char.
You need to change something. Passing big things in functions is asking for a pointer
If comb take an array
void comb(int n, int array[n])
this should be put like
void comb(int n, int*array)
And then access to elements are in the fashion
*(array+k) ... // equals to array[k]
YOU CANNOT DO THIS
array[k] ... // Erro.
And call comb in main just in the way you did, since array names are already pointers
Not sure for bidimentional but almost sure the same, since bidim are just a big unidimensional array arranged in another way.
When passing pointer, function forget about boundaries.
Good practice is to help the function avoid disasters passing the max len
void comb(int n, int*array,int len)
{
int k=0;
While(*(array+k) !=n) // Search array for a number equal to "n".....
{
k++;
if(k>len)
return 0; // Avoid seeking outside the array, cut now. nice plase to return 0 (not found)
}
return 1; // got a hit before reaching the end.
}
Meanwhile in the main call:
comb(p, array, sizeof(array)/sizeof(array[0]); // third param is the number of elements

Resources