arrays in C (mixing two arrays) [closed] - arrays

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
I can't figure out why is my program not working. Can someone from the experts help? :)`
I'm getting storage junk numbers in my console, my third array should be a mix of array aA[] and aB[], first goes the elements from array aA[] then from aB[] once at the time.
// 2te Vektor HÜ
// Bsp.: aA[7, 8, 9] aB[14, 15, 16]
// => aC[7, 14, 8, 15, 9, 16]
// returns size of C`int val = 0;
`````````````````````````````````
int Mischen(int aA[], int aB[], int aC[], int aLaenge) {
int val = 0;
val = aLaenge;
for (int i = 0; i < aLaenge; i++) {
int c = 0, x = 1;
c = c += 2;
x = x += 2;
aC[c] = aA[i], aC[x] = aB[i];
}
return val;
}

You simplify the loop. Remember, you need to copy the values from the source arrays to the alternate index in the destination array. To elaborate,
aA[0], aA[1], aA[2].. should go to aC[0], aC[2], aC[4]...
aB[0], aB[1], aB[2].. should go to aC[1], aC[3], aC[5]...and so on.
So the logic can be
Copy the value at aA[i] to aC[2*i].
Copy the value at aB[i] to aC[(2*i)+1].
So, change it to
for (int i = 0; i < aLaenge; i++) {
aC[2*i] = aA[i];
aC[(2*i)+1] = aB[i];
}

You can change the code like this way, you should defined the variable c and x outside the loop and every time increase them by two.
int Mischen(int aA[], int aB[], int aC[], int aLaenge) {
int val = 0;
val = aLaenge;
int c = 0, x = 1;
for (int i = 0; i < aLaenge; i++) {
//int c = 0, x = 1;
//c = c += 2;
//x = x += 2;
aC[c] = aA[i];
aC[x] = aB[i];
c += 2;
x += 2;
}
return val;
}

Related

Segmentation fault with concatenation of two strings

I'm trying to build alphanumeric strings consisting of 3 initial letters and 3 final numbers and save them in a .txt file. I wrote this:
int i = 0,
j = 0;
char name_cpu[8],
array_numbers_final[8],
array_letters[27] = "ABCDEFGHIJKLMNOPQRSTUWXYVZ",
array_numbers[10] = "123456789";
/* Generator data */
for(i = 0; i < number_cpu; i++)
{
for(j = 0; j < 3; j++){
name_cpu[j] = array_letters[rand() % (sizeof(array_letters)-1)];
array_numbers_final[j] = array_numbers[rand() % (sizeof(array_numbers)-1)];
}
strcat(name_cpu, array_numbers_final);
fprintf(list_cpu, "%s \n", name_cpu);
}
The problem is that at the first external for loop it correctly prints a string of the form "AAA000". At the second for loop it goes in segmentation fault. Can anyone tell me what and where I am doing wrong?
EDIT:
A minimal reproducible example is:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (void){
FILE *list_cpu = NULL;
int i = 0,
number_cpu = 3,
j = 0;
char name_cpu[8] = {0},
array_numbers_final[8] = {0},
array_letters[27] = "ABCDEFGHIJKLMNOPQRSTUWXYVZ",
array_numbers[10] = "123456789";
list_cpu = fopen("list_cpu.txt", "w");
/* Generator data */
for(i = 0; i < number_cpu; i++)
{
for(j = 0; j < 3; j++){
name_cpu[j] = array_letters[rand() % (sizeof(array_letters)-1)];
array_numbers_final[j] = array_numbers[rand() % (sizeof(array_numbers)-1)];
}
strcat(name_cpu, array_numbers_final);
fprintf(list_cpu, "%s \n", name_cpu);
}
fclose(list_cpu);
return(0);
}
If number_cpu is equal to 1 it works. But if it is higher then 1, the program goes into segmentation fault.
answer to new edits to OP
Edits to OP include initialization of variables addressing some instances of undefined behavior in original code, however buffer overflow problem remains in following section:
/* Generator data */
for(i = 0; i < number_cpu; i++)
{
for(j = 0; j < 3; j++){
name_cpu[j] = array_letters[rand() % (sizeof(array_letters)-1)];
array_numbers_final[j] = array_numbers[rand() % (sizeof(array_numbers)-1)];
}
strcat(name_cpu, array_numbers_final);
fprintf(list_cpu, "%s \n", name_cpu);
}
fclose(list_cpu);
Where name_cpu is defined with 8 char: char name_cpu[8] = {0}
"If number_cpu is equal to 1 it works. But if it is higher then 1, the program goes into segmentation fault."...
After first iteration of outer loop, including one strcat of name_cpu and list_cpu, the char name_cpu is populated with 6 new characters and \0 in remaining locations. Eg:
//example
|S|J|P|Y|E|P|\0|\0| //
The error occurs at end of 2nd iteration of outer loop at the strcat() statement. The inner loop re-populated the first three positions of name_cpu, eg:
//first three positions changed, the rest remains
|C|B|A|Y|E|P|\0|\0| //
^ ^ ^ updated values
Error occurs when the new value for array_numbers_final :
|G|H|O|\0|\0|\0|\0|\0|
is attempted to be concatenated to name_cpu, resulting in:
|C|B|A|Y|E|P|G|H|O| //attempt to write to memory not owned
^end of buffer
Resulting in buffer overflow error, and likely the segmentation fault error condition.
Again, as before, design variables to meet the potential needs of of the program. In this instance the following will work:
char name_cpu[100] = {0};
char array_numbers_final[100] = {0};
answer to original post:
The problem is here:
strcat(name_cpu, array_numbers_final);//undefined behavior.
First, name_cpu[8] is uninitialized at time of declaration, nor is it initialized at any time before used. Because it is not guaranteed what the contents are, it is not necessarily a string. Using this variable as is in any string function can invoke undefined behavior
Furthermore,(even if name_cpu is a valid string) when array_numbers_final is concatenated to name_cpu, the buffer will overflow. During my test run I saw this:
The fix is to start off with initialized buffers of sufficient size for intended purpose. eg:
char name_cpu[100] = {0}
array_numbers_final[100] = {0},
array_letters[27] = "ABCDEFGHIJKLMNOPQRSTUWXYVZ",
array_numbers[10] = "123456789";
Code example below is adaptation using your provided example, with suggested edits. Read in-line comments:
int main(void)
{
int number_cpu = 3;//added - previously not defined in OP
int i = 0,
j = 0;
char name_cpu[100] = {0},//resized and initialize
array_numbers_final[100] = {0},//resized and initialize
array_letters[27] = "ABCDEFGHIJKLMNOPQRSTUWXYVZ",
array_numbers[10] = "123456789";
/* Generator data */
for(i = 0; i < number_cpu; i++)
{
for(j = 0; j < 3; j++){
name_cpu[j] = array_letters[rand() % (sizeof(array_letters)-1)];
array_numbers_final[j] = array_numbers[rand() % (sizeof(array_numbers)-1)];
}
strcat(name_cpu, array_numbers_final);
fprintf(stdout, "%s \n", name_cpu);//to stdout
// ^ changed here
}
return 0;
}

Segmentation fault (core dump) with multiplication of dynamic matrices [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 3 years ago.
Improve this question
I'm writing this code but it's continue on giving me a core dump error but i cannot understand why...This code takes 4 int inputs and two double matrices and gives me two outputs (result and the product matrix). I think the problem is in the allocation but I'm not sure... Thanks in advance for your help!
double **calculate product (double** matrix1,
double** matrix2,
int *result,
int dim_rows1,
int dim_rows2,
int dim_col1,
int dim_col2)
{
int i, j, k;
double** prod_matrix = NULL;
if(matrix1 == NULL || matrix2 == NULL)
*result = 0;
else
{
*result = 1;
if(dim_col1 == dim_rows2)
{
prod_matrix = (double **)malloc((dim_rows1)*sizeof(int *));
for(i = 0; i < dim_rows1; i++)
{
prod_matrix[i] = (double *)malloc((dim_col2)*sizeof(int));
}
for(i = 0; i < dim_rows1; i++)
{
for(j = 0; j < dim_col2; j++)
{
prod_matrix[i][j] = 0;
for(k = 0; k < dim_rows2; k++)
{
prod_matrix[i][j] += matrix1[i][k]*matrix2[k][j]
}
}
}
}
else
*result = 0;
return(prod_matrix);
}
An example of main is:
int main (void){
int result,
dim_col1,
dim_col2,
dim_rows1,
dim_rows2,
selected;
double **matrix1 = NULL,
**matrix2 = NULL,
**sum_matrix = NULL,
**prod_matrix = NULL;
selected = text(); /* client chose a number beetween 1 and 6*/
switch(selected)
{
case 1: /* case 1 and case 2 take the dimension of the matrix */
.
.
.
case 5: /* makes sum beetween matrix */
.
.
case 6: prod_matrix = prod_matrix (matrix1, matrix2, &result, dim_rows1 . . . dim col2)
if(result == 1)
//do things
else
//do things
}
return(0);
}
I forgot to say, usally it works but when i try with the first one matrix (4,2) and the second one (3,4) it goes always in segmentation fault.
Eljay has it.
prod_matrix[i] = (double *)malloc((dim_col2)*sizeof(int));
should be
prod_matrix[i] = (double *)malloc((dim_col2)*sizeof(double));

Unable to read memory. Can't find what's wrong

I've got a piece of code, it's purpose is to draw a background image on one of the game levels. For this purpose I create this structure.
typedef struct crate_t {
int x = 0;
int y = 0;
int h = 0;
int w = 0;
int type = BACKGROUND;
}crate;
Then in the main function I create a 2D array
crate **Crates = (crate**)malloc(sizeof(crate)*(SCREEN_WIDTH / GrassBlock->w));
for (int i = 0; i <= SCREEN_HEIGHT/GrassBlock->h; i++) {
Crates[i] = (crate*)malloc(sizeof(crate)*(SCREEN_HEIGHT / GrassBlock->h));
}
and I pass it to the function counter = DrawLevelBG(screen, GrassBlock, Border, Crates);. The problem is that the function causes error. "Access violation writing location." at Obstacles[i][j].x = x;
int DrawLevelBG(SDL_Surface *screen, SDL_Surface *sprite, SDL_Surface *border, crate **Obstacles) {
int x = 0;
int y = 0;
int i = 0;
int j = 0;
bool condition = 0;
while (y < SCREEN_HEIGHT + sprite->h) {
DrawSurface(screen, sprite, x + (sprite->w / 2), y + (sprite->h / 2));
if (x >= SCREEN_WIDTH - sprite->w || x == 0 || y == 0 || y >= SCREEN_HEIGHT - sprite->h) {
DrawSurface(screen, border, x + (sprite->w / 2), y + (sprite->h / 2));
Obstacles[i][j].x = x;
Obstacles[i][j].y = y;
Obstacles[i][j].h = border->h;
Obstacles[i][j].w = border->w;
Obstacles[i][j].type = WALL;
i++;
if (x >= SCREEN_WIDTH - sprite->w) {
y += sprite->h;
x = 0;
j++;
condition = 1;
}
}
if (!condition) {
x += sprite->w;
}
condition = 0;
}
return i;
}
I know that these ones are caused by pointers not pointing actually to anything but I can't understand what's wrong here. Any help would be greatly appreciated. Thanks.
EDIT
I've changed my memory allocation piece of code so it looks like that now:
crate **Crates = (crate**)malloc(sizeof(crate*)*(SCREEN_WIDTH / GrassBlock->w)*(SCREEN_HEIGHT / GrassBlock->h));
for (int i = 0; i <= SCREEN_WIDTH/GrassBlock->w; i++) {
Crates[i] = (crate*)malloc(sizeof(crate)*(SCREEN_HEIGHT / GrassBlock->h));
}
According to all your replies guys. Unfortunately this doesnt solve the problem. +Important info, the function DrawLevelBG causes ERROR on the first iteration of loop.
In the first allocation you create an array from pointers. So you need to allocate memory for pointers:
crate **Crates = (crate**)malloc(sizeof(crate*)*(SCREEN_WIDTH / GrassBlock->w));
Thanks for all the help guys. The problem was iterators, not only did I make my 2D array SCREEN_HEIGHT wide and SCREEN_WIDTH high which was the opposite of what I wanted but aswell the iteration in DrawLevelBG was wrong as pointed out. I had to swap my "i" and "j" and make some corrections, so thanks alot Some programmer dude for pointing that out. Thanks alot.

C Array being overwritten? [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
When I run this program : http://hastebin.com/asorawoluw.m
I get this error in GDB :
Program received signal SIGSEGV, Segmentation fault.
0x0000000000401f91 in resoudre (baie=...) at lineaire.c:291
291 printf("type[%d] : %d\n", i, helper_glpk.col_bounds[i]->type);
When i ask gdb to print iI get :
$1 = 1
So the first iteration is failing, but I'm sure I did write into the first case of helper_glpk.col_bounds at the line 200-204 and I did malloc so there's no way (I think ?) that my data is being overwritten or deleted.. so I don't understand why I get this error.
Edit : here's the minimal code :
My structs :
typedef struct Bounds Bounds;
struct Bounds
{
int type;
double lb;
double ub;
};
typedef struct HelperGlpk HelperGlpk;
struct HelperGlpk
{
double *matrix_coefs;
double *obj_coefs;
Bounds **row_bounds;
Bounds **col_bounds;
int *column_of_coef;
int *row_of_coef;
int cpt_coef;
int cpt_contrainte;
};
My functions to generates constraint :
void genere_contrainte_1(int i, int j, HelperGlpk *helper_glpk, Baie baie){
helper_glpk->col_bounds[index_ouverture_serveur(i)]->type = GLP_DB;
helper_glpk->col_bounds[index_ouverture_serveur(i)]->lb = 0;
helper_glpk->col_bounds[index_ouverture_serveur(i)]->ub = 1;
helper_glpk->cpt_coef++;
helper_glpk->col_bounds[index_connexion(i, j, baie.nbr_serveur)]->type = GLP_LO;
helper_glpk->col_bounds[index_connexion(i, j, baie.nbr_serveur)]->lb = 0;
helper_glpk->col_bounds[index_connexion(i, j, baie.nbr_serveur)]->ub = 0;
helper_glpk->cpt_coef++;
}
and the main program is :
void resoudre(Baie baie){
glp_prob *lp;
const int nbr_rows = baie.nbr_client + baie.nbr_serveur * baie.nbr_client; // nombre de contrainte
const int nbr_colums = baie.nbr_serveur + baie.nbr_serveur * baie.nbr_client; // nombre de variable
const int nbr_coefs = 3 * baie.nbr_serveur * baie.nbr_client;
int i, j;
HelperGlpk helper_glpk;
helper_glpk.matrix_coefs = malloc((nbr_coefs + 1) * sizeof(double));
helper_glpk.matrix_coefs[0] = 0;
helper_glpk.obj_coefs = malloc((nbr_colums + 1) * sizeof(double));
helper_glpk.obj_coefs[0] = 0;
helper_glpk.column_of_coef = malloc((nbr_colums + 1) * sizeof(int));
helper_glpk.column_of_coef[0] = 0;
helper_glpk.row_of_coef = malloc((nbr_rows + 1) * sizeof(int));
helper_glpk.row_of_coef[0] = 0;
helper_glpk.col_bounds = malloc((nbr_colums + 1) * sizeof(Bounds *));
for (int index = 0; index <= nbr_colums; index++)
{
helper_glpk.col_bounds[index] = malloc(sizeof(Bounds));
}
helper_glpk.row_bounds = malloc((nbr_rows + 1) * sizeof(Bounds *));
for (int index = 0; index <= nbr_rows; index++)
{
helper_glpk.row_bounds[index] = malloc(sizeof(Bounds));
}
helper_glpk.cpt_coef = 1;
for(i = 1; i <= baie.nbr_serveur; i++)
for(j = 1; j <= baie.nbr_client; j++)
genere_contrainte_1(i, j, &helper_glpk, baie);
for(i = 1; i <= nbr_colums; i++)
printf("type[%d] : %d\n", i, helper_glpk.col_bounds[i]->type);
for(j = 1; j <= baie.nbr_client; j++)
genere_contrainte_2(j, &helper_glpk, baie.nbr_serveur);
The error I get is while I try to printf after the call to generate_contrainte_1
This code is wrong:
helper_glpk.col_bounds = malloc((nbr_colums + 1) * sizeof(Bounds));
You need to fix it with (provided you need nbr_colums + 1 elements):
helper_glpk.col_bounds = malloc((nbr_colums + 1) * sizeof(Bounds *));
for (int index = 0; index < nbr_colums + 1; index++)
{
helper_glpk.col_bounds[index] = malloc(sizeof(Bounds));
}
I have not checked the rest of the code, there could be other errors.
Edit: maybe you don't need the for loop depending on what your genere_contrainte_1 does, but you need to correct your malloc with the right sizeof.
Edit2: I read your genere_contrainte_1, you definitely need all these mallocs. But I really doubt you need row_bounds and col_bounds to be Bounds **, it seems to me Bounds * would have been fine, and that way a single malloc for each field would be enough.

What's wrong with my for loop?

I am making a game using lite-C (exactly same syntax as C). and I cannot make this loop work.
It gives me an error at this line at compilation.
for(int i = 0; i < (cantenemigu * 3); i += 3)
I have an array with the information of where to create the enemies.
the array contains the x,y,z coordinates.
cantenemigu is the amount of enemies that there are in the array.
With this loop I would get the information of each enemy and create it.
[EDIT]
The answers didn't work. I added the ; acsidently while writing the post.
Maybe the problem is somewhere else;
Here is the hole part.
int cantenemigu = 3;
var posenemigu[] = {-900, 550, -10, -1100, 1600, -10, 70, 1680, 20};
void load_enemigunan()
{
for(int i = 0; i < (cantenemigu * 3); i += 3)
{
ent_create("targetr.mdl",vector(posenemigu[i],
posenemigu[i + 1],
posenemigu[i + 2]),NULL);
}
}
This is the code if I don't add the <br>
I solved it.
this worked.
int i
for(i = 0; i < 3*cantenemigu; i += 3)
{
ent_create("targetr.mdl",vector(posenemigu[i],
posenemigu[i + 1],
posenemigu[i + 2]),NULL);
}
In C# it doesn't have be declared before. I assumed it was also so in C. (or maybe it's a bug in the compiler).
for (int i = 0; i < (cantenemigu * 3); i += 3)
There should not be any ; after i += 3.
Try changing your code to this: (note what I've done is move the declaration of i outside the for loop.
int cantenemigu = 3;
var posenemigu[] = {-900, 550, -10, -1100, 1600, -10, 70, 1680, 20};
void load_enemigunan(){
int i;
for(i = 0; i < (cantenemigu * 3); i += 3){
ent_create("targetr.mdl",vector(posenemigu[i],
posenemigu[i + 1],
posenemigu[i + 2]),NULL);
}
}
Get rid of the 3rd ;.
for(int i = 0; i < (cantenemigu * 3); i += 3)
It looks like you are missing a closing parenthesis for your call to vector.
ent_create(
"targetr.mdl",
vector(
posenemigu[i],
posenemigu[i + 1],
posenemigu[i + 2],
NULL
);
for(int i = 0; i < (cantenemigu * 3); i += 3;)
What is the error? That last semicolon shouldn't be there.
What is the body of the loop?
What type of variable is cantenemigu? Can it be coerced to int?

Resources