I'm having an issue with printing out my struct array. It is initialized like so:
struct matrix tokens[nbrState][12];
I then try to print it out with this code:
printf("%d", tokens[0][0].state);
for(int q = 0; q < nbrState; q++){
for(int r = 0; r < 12; r++){
printf("%d", tokens[q][r].state);
}
}
How ever it just gives back
160833216083325909500442637211181530452359314445659095247095039827295039732859091035295039760059091066417471141950397584105931452485931525045870278695909110245869685280135590599950397784950397744593145248159314402459314316859095284905931452481590950044135934508013593144456590952470095039760058696836095039787258698266456147669503978565869965120593144552593143168419536358702168841950960596593143168950398056950398016593144552159315536059315450459095284905931445521015931545041048576587404166341899271605931553609503978729503978563593450804195363-1141298268758698266459314316800419611295039881600950398592587297673016950398176950397984091005908849605884315520000050-100950398592419
And I'm not sure why. I'm also filling the array with values using this for loop.
while ( fscanf ( fp, "%d/%d%c", &index, &separateInt, &separateChar) == 3) {
for(int i = 0; i < 12; i++){
tokens[index][i].state = separateInt;
}
}
You said
It is initialized like so
struct matrix tokens[nbrState][12];
But the above declaration does not initialize anything (unless your array is declared with static storage duration). A local array declared in this fashion will contain garbage at the beginning. That's apparently what you are printing.
If you want your array initialized, you have to initialize it yourself. For example, this declaration
struct matrix tokens[nbrState][12] = { 0 };
will initialize everything with zeros, assuming nbrState is a constant.
If nbrState is not a constant, then you will not be able to use a = { ... } initializer in the declaration. You will have to assign the initial values to your array elements manually, using a cycle or in some other way.
Related
I have my pseudocode something like this in C. I have some part of data stored in data structure, but im struggling to have another set of data (based on an if condition) to store in a separate array which is not fixed size. Any suggestion is appreciated.
typedef struct struct1 {
uint32 member1
} PACKED struct1_t
typedef struct struct2 {
struct1_t *member2
} PACKED struct2_t
uint32 curnt_cnt = 0;
for (i=0; i<some_number; i++){
if (cond) {
k = m;
struct2_t->member2[curnt_cnt].member1 = k; #I have no prob writing here
}
else {
k = n;
array[curnt_cnt] = k; ==> Is this even correct implementation?
# I want to store/ book-keep the values of k in an array throughout every iteration of for loop without overwriting the previous value
# Size of the array will not exceed "some_number (mentioned in for loop)" at any time
}
curnt_cnt++;
}
You must create a pointer, since lists in C must have a specific size
int* arr;
arr = (int*)malloc(sizeof(int)*some_number);
and then in your code
else {
k = n;
array[curnt_cnt] = k;
}
will work.
I'm Trying to check in my matrix of dimension [10][10], which spots are available to store data (String) there and which are occupied.
The code basically goes through the whole matrix and checks every spot.
I have tried using the strlen and != NULL but everything just prints that the spot is free.
char parque[10][10];
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
parque[i][j] = "";
}
}
parque[5][5]="f47ac10b-58cb-4372-a567-0e02b2c3d499,ANR";
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
if(parque[i][j] != "") {
printf("The Spot [%d][%d] is taken",i,j);
} else {
printf("The Spot [%d][%d] is free",i,j);
}
}
}
Basically the spot [5][5] should print that it's taken, at least that's what I want it to do...
Thanks in advance!
Your declaration
char parque[10][10];
declares a two-dimensional array of char. If you compile your code with a strict compiler, you'll get an error:
error: assignment makes integer from pointer without a cast [-Wint-conversion]
parque[i][j] = "";
^
What you did mean is to make an array of pointers to const char, like here:
const char* parque[10][10];
Then your program will say that The Spot [5][5] is taken.
You can't use !=. You need to use strcmp. And, of course, you need to initialize your array content before iterating it and using its values to compare with "" string.
This condition:
if(parque[i][j] != "")
Will become:
if (strcmp(parque[i][j], ""))
First of all,the names of variables are in greek.
It's impossible to saw all the code,because is many files.
However a have a struct
typedef struct{
TTamias* Tamies;
}TPinakasTamiwn;
And TTamias is type
typedef struct{
int time_busy; /*xronos apasxolhshs tou tamia*/
int time_inactive; /*xronos pou o tamias einai adranhs*/
int arithos_pelaton; /*posous pelates eksipiretise o tamias*/
int enapomenon_xronos; /*enapomenon xronos eksipiretisi enos pelath*/
}TTamias;
With this function in main i create an array
void DimourgiaTamiwn(TPinakasTamiwn* tamias)
{
tamias->Tamies = (TTamias*)malloc(sizeof(TTamias) * TAMIES);
}
After some comparisons i want to raise the size of array with this function
int ProsthikiTamia(TPinakasTamiwn* tamias,int plithos_tamiwn)
{
TTamias* NeoiTamies;
int neo_plithos = plithos_tamiwn + 1;
NeoiTamies = (TTamias*)malloc(sizeof(TTamias) * neo_plithos);
for(int i = 0; i < plithos_tamiwn; i++)
NeoiTamies[i] = tamias->Tamies[i];
for(int i = neo_plithos - plithos_tamiwn; i < neo_plithos; i++)
TamiasDimiourgia(&NeoiTamies[i]);//fuction to initialize the data member of extra index
tamias->Tamies = (TTamias*)realloc(tamias->Tamies , neo_plithos);// <-----PROBLEM
for(int i = 0; i < neo_plithos; i++)
tamias->Tamies[i] = NeoiTamies[i];
free(NeoiTamies);
return neo_plithos;
}
The function return the new size that is raise than one.
I create a local array and copy to that the main array,
i want to reallocate the main array and copy again the local array to new main array.
Doesn't appear compile error,but in execution (also at debug) the program break at realloc.
When reallocating, you have forgotten to multiply the dimension by the unit size. The correct line shall be:
tamias->Tamies = (TTamias*)realloc(tamias->Tamies , sizeof(TTamias) * neo_plithos);
let's say I have a functions below.
void function createBands(boolean option) {
int i, j;
int ***bands = (int ***)malloc((SIZE + 1) * sizeof(int **));
for (i = 0; i < SIZE; i++) {
bands[i] = (int **)malloc(HEIGHT * sizeof(int *));
for (j = 0; j < HEIGHT; j++)
bands[i][j] = (int *)malloc(WIDTH * sizeof(int));
}
iterator *it =
createIterator(params); // do not be confused it is a structure with
// methods andaeribute just like Iterator class in
// java . Methods are poniters to functions.
repare_array(bands[Size], it);
}
void prepare_array(int **band, iterator *it) { read_array(band, it); }
read_array(int **band, iterator *it) {
for (int i = 0; i < Height; i++)
band[i] = (int *)it->next();
}
// Now in Iterator.c I have the iterator structure with the methods etc I will
// write just some line form iterator.
void *next() {
byte *b =
a function that reads bytes form a file and returns byte * CORECTLY !!!;
return b == NULL ? NULL : bytetoT(b);
// this function make void form byte conversion but it doesnt work so I make
// only a cast in read_aray as you see. SUppose just return b wich is byte(i
// know in C isn't any byte but I redeclared all the types to be JAVA.)
}
the questions is where I should allocate the bands because in this situation the 1D vector return by function is ok because I see the values in the function scope. But when it is return to array[i] I got a unallocated 3dVector.
I need to recieve bands[size][i][j] with the data form b. In b the data is good then I ve gote bands null.
What I have do so far I make another allocation in prepare aray before the call to read_array where I allocate **band and then I have some results but I am not confident.
Sorry for the confusion! And every comment is good for me. Maybe what I have do is ok I do not know!.
I am not new to C I just do not work with pointers for a long time.
If it is a 2D pointer(**) you have to assign it with the address of 2D array and if it is 1D array you have to assign it with the address of 1D array.
For your read_array function
read_array(int**array...)
{
for(i=0;i<HEIGHT(the same as in allocation);i++)
`enter code here`array[i] = function();//function return an 1D array
}
Make sure that function() returns the address of the 1D array.
I have what I consider a really strange problem. I have a function with the following prototype:
void generateNodes(const int maxX, const int maxY, node nodes[]);
As one of the first things in this function I define a 2d array of shorts, which i use as boolean values. But when I call this function the value of maxY changes to a large value. The code in question is below:
void generateNodes(const int maxX, const int maxY, node nodes[]){
int i, currentX, currentY;
short used[MAX_NODES][MAX_NODES];
//Generate the nodes
for(i = 0; i < MAX_NODES; i++){
currentX = randomNumber(0,maxX);
currentY = randomNumber(0,maxY);
nodes[i].color = 0;
nodes[i].numberOfConnections = 0;
nodes[i].id = i;
nodes[i].distanceFromStart = NOT_SET;
nodes[i].parent = NULL;
if(!used[currentX][currentY]){
nodes[i].x = currentX;
nodes[i].y = currentY;
used[currentX][currentY] = 1;
} else {
i--;
}
}
int numberOfConnections, j, currentNeighbor;
//Generate the connections
for(i = 0; i < MAX_NODES; i++){
numberOfConnections = randomNumber(1,5); //Between one and five outgoing connections
for(j = 0; j < numberOfConnections; j++){
currentNeighbor = randomNumber(0,19); //Select the neighbor
while(currentNeighbor == i){
currentNeighbor = randomNumber(0,19); //Try again while the selected is self
}
nodes[i].canReach[++(nodes[i].numberOfConnections)] = &nodes[currentNeighbor];
nodes[currentNeighbor].canReach[++(nodes[currentNeighbor].numberOfConnections)] = &nodes[i];
}
}
}
MAX_NODES is defined to 20.
Does anyone know why this might happen?
Very probably the code in ... is accessing beyond the end of used, causing arguments to be smashed. Without the code, it's of course impossible to say.
Since you do not seem to initialize the array used, it may well be that some elements are considered used (!= 0), since an array on stack is not initialized to zero, but takes whatever was in that memory area before.
An if an X,Y pair is considered used, you decrement the loop counter, possibly beyond zero into the negative realm, possibly overwriting - on the next iteration - part of the stack. This may also change the parameters, since they also reside on the same stack, before the local array.
Start with initializing used, and consider rewriting the loop to not change the loop variable except in the for statement.