strange behaviour when printing a float and then an Array - c

I try to print out two arrays with the following function using XCode 6.1.1:
for (int j=0; j<4; j++) {
for (int k=0; k<4; k++) {
printf("%2d ", Lattice[0][j+N*k]);
}
printf(" ");
for (int k=0; k<4; k++) {
printf("%2d ", Lattice[1][j+N*k]);
}
printf("\n");
}
printf("\n");
Everything works fine when calling the function,
as long as I don't print out a float before.
When printing an int, there's no problem. So it's a
little strange, right?
I'm initializing the array like this:
int **Lattice = (int**)malloc(2*sizeof(int*));
if (Lattice == NULL) return NULL;
for (int i=0; i<2; i++){
Lattice[i] = (int *)malloc(2*sizeof(int));
if (Lattice[i] == NULL) {
for (int n=0; n<i; n++)
free(Lattice[n]);
free(Lattice);
return NULL;
}
else{
for (int j=0; j<N; j++) {
for (int k=0; k<M; k++) {
Lattice[i][j+N*k] = 0;
}
}
}
}
return Lattice;
Too bad, I can't upload an image of the output.
The matrices should show only zeros, but with the float
there will be big numbers in some entries which i can't explain.
I'm grateful for any hints.
Thank you.

So your code has some pretty serious problems.
Lattice[0] and Lattice[1] need to have dimensions 4x4 for your printing block of code to make any sense. Incidentally this means N and M need to equal 4 as well or you need to change your printing for loop conditions to j < N and k < M respectively.
Your malloc needs to allocate space for that as well, so: Lattice[i] = (int *)malloc(N * M * sizeof(int));
This should cause your loops to work correctly, but you do not have floats anywhere in your code. You cannot use printf to print an int as a float. The value will not be promoted. It will simply be treated as a float.

Related

using C copy a 1D char array into 2D char array

I am trying to copy a 1D array of Strings into a 2D array of strings in C.
I was able to achieve this with integer
enter image description here
//Here is what I tried for integers.
int main()
{
int arr[3][3];
int arr2[9]={1,2,3,4,5,6,7,8,9};
int i,j,k=0;
for(i=0; i<3;i++){
for(j=0; j<3;i++){
arr[j][i] = arr2[i];
//rintf("%d\n",arr2[i]);
}
}
for(i=0; i<3; i++) {
for(j=0; j<3; j++)
printf("%2d ", arr[j][i]);
printf("\n");
}
return 0;
}
I changed my data to char and I tried to run the same code I got a segmentation error.
Here is what I have tried so far and it didnt work. error :Segmentation fault (core dumped)
#include<stdio.h>
#include<string.h>
int main()
{
char *d[3][3]; // Destination array
char *s[9]={"orange","apple","table","chair","cable","TV", "124","HI"}; // Source 1 Day array
int i,j,k=0;
for(i=0; i<3;i++){
for(j=0; j<3;i++){
strcpy(d[j][i], s[i]);
}
}
for(i=0; i<3; i++) {
for(j=0; j<3; j++)
printf("%s ", d[j][i]);
printf("\n");
}
return 0;
}
I have made some adjustment and now it print some weird strings
#include<stdio.h>
#include<string.h>
int main() {
char d[3][3] ={0}; // Destination array
char s[9][8]={"orange","apple","table","chair","cable","TV", "124","HI"}; // Source 1 Day array
int i,j,k=0;
for(i=0; i<3;i++){
for(j=0; j<3;j++){
d[j][i] = *s[i];
}
}
for(i=0; i<3; i++) {
for(j=0; j<3; j++)
printf("%s ", &d[j][i]);
printf("\n");
}
return 0;
}
enter image description here
This for loop
for(i=0; i<3;i++){
for(j=0; j<3;i++){
arr[j][i] = arr2[i];
//rintf("%d\n",arr2[i]);
}
}
is incorrect. In the inner loop there are used the same elements arr2[i] where i is changed from 0 to 2 inclusively.
You need to write
for(i=0; i<3;i++){
for(j=0; j<3;i++){
arr[j][i] = arr2[ 3 * i + j];
}
}
Another way to write loops is the following
for ( i = 0; i < 9; i++ )
{
arr[i / 3][i % 3] = arr2[i];
}
As for arrays of pointers of the type char * then the nested loops will look similarly
for(i=0; i<3;i++){
for(j=0; j<3;i++){
d[i][j] = s[ 3 * i + j];
}
}
provided that the array s is declared like
char * s[9]={"orange","apple","table","chair","cable","TV", "124","HI"};
And to output the result array you need to write
for(i=0; i<3; i++) {
for(j=0; j<3; j++)
printf("%s ", d[i][i]);
^^^^^^^
printf("\n");
}
As for your last program then it can look like
#include<stdio.h>
#include<string.h>
int main( void )
{
char d[3][3][8] ={0}; // Destination array
char s[9][8]={"orange","apple","table","chair","cable","TV", "124","HI"}; // Source 1 Day array
for( size_t i = 0; i < 3; i++ )
{
for ( size_t j = 0; j < 3;j++ )
{
strcpy( d[j][i], s[3 * i + j] );
}
}
for ( size_t i = 0; i < 3; i++ )
{
for ( size_t j = 0; j < 3; j++ )
{
printf( "%s ", d[i][j] );
}
putchar( '\n' );
}
return 0;
}
Some issues ...
d is unitialized so the pointers within point to random locations.
To fix, we need to use malloc to get space and then do strcpy. An easier way is to just use strdup. Or, just assign the s value directly.
Your j loop should increment j and not i.
Using s[i] will repeat after three elements. To fix, we can do: s[k++]
You are short one initializer for s (i.e. it is length 9 but you have only 8 strings).
Here is the refactored code:
#include <stdio.h>
#include <string.h>
int
main(void)
{
char *d[3][3]; // Destination array
char *s[9] = {
"orange", "apple", "table", "chair", "cable", "TV", "124", "HI",
#if 1
"raindrops"
#endif
}; // Source 1 Day array
int i, j, k = 0;
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
// NOTE/BUG: we must allocate space for d[j][i]
#if 0
strcpy(d[j][i], s[i]);
#else
d[j][i] = strdup(s[k++]);
#endif
}
}
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++)
printf("%s ", d[j][i]);
printf("\n");
}
return 0;
}
Here is the output:
orange apple table
chair cable TV
124 HI raindrops
There's numerous big problems here.
You could have simply solved this with memcpy(arr, arr2, sizeof *arr2);
(Probably the least of your problems, but...) This is badly written performance-wise: for(j=0; j<3;i++){ arr[j][i] = arr2[i]; Multiple loops should always have the inner-most loop work with the inner-most array item, in this case it should have been arr[i][j], or you get needlessly bad data cache performance.
for(j=0; j<3;i++) How about j++.
char *d[3][3]; is an uninitialized 2D array of pointers, each pointing at la-la-land. So you can't copy jack into those addresses - pointers need to point at valid, allocated memory.
char d[3][3] is a 2D array of 3x3 characters, so it can't contain the data you wish to store there, let alone the mandatory null terminators required for strings to work.
char *s[9] = ... In case you meant the 9th item to be NULL, a so-called sentinel value, you should type out NULL explicitly or otherwise the reader can't tell if a NULL sentinel is intended or if you just sloppily added one by accident.
As you can tell from previous comments, the overall slopiness is a recurring major problem here. Take for example:
for(j=0; j<3; j++)
printf("%s ", &d[j][i]);
printf("\n");
Because of sloppy indention, we can't tell if the printf("\n"); was intended to sit inside the inner loop or not (it is not, despite the indention). You can't just type some almost correct stuff down in a hurry. You have to carefully type down actually correct code. There's various myths that great programmers are smart, great at math or abstract thinking etc - in reality, great programmers are careful and disciplined, taking some pride in their own craft.
The quick & dirty fix is to use the second example char* d[3][3] and then instead of strcpy use strdup (currently non-standard, soon to become standard):
for(size_t i=0; i<3; i++){
for(size_t j=0; j<3; j++){
d[i][j] = strdup(s[i]);
}
}
(And ideally also call free() for each item in d at the end.)
But the root problem here is that you need to go back and carefully study arrays, pointers and strings, in that order, before using them.

Dereferencing pointer to a pointer doesn't work when I pass it to a function. Why? (C)

I tried everything I could think off. I don't know if I'm missing something obvious. Why does this work:
#include<stdio.h>
void test_matrix(int** matrix)
{
for(int i=0; i<4; i++) {
for(int j=0; j<4; j++) {
printf("%d ", *(matrix+j+4*i));
}
}
/**
for(int i=0; i<4; i++) {
for(int j=0; j<4; j++) {
printf("%d ", *(*(matrix+i)+j));
}
}
*/
}
int main()
{
int matrix[4][4];
for(int i=0; i<4; i++)
for(int j=0; j<4; j++)
scanf("%d", &matrix[i][j]);
test_matrix(matrix);
}
But the commented section doesn't work. I also tried matrix[i][j] and it still won't work. My program times out.
EDIT: I added the function calling in MAIN.
The error is that this 2D-array is laid out as 4 x 4 = 16 integers. But your function expects a pointer to pointers.
It's right that at the calling site the address of matrix is provided as the argument. But unlike some commenter said, it's not a pointer to int but a pointer to an int-array.
To handle this address of the 2D-array correctly you need to tell it your function, like this:
void test_matrix(int (*matrix)[4])
{
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
printf("%d ", *(*(matrix + i) + j));
}
}
}
or like this:
void test_matrix(int matrix[][4])
{
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
printf("%d ", matrix[i][j]);
}
}
}
Which kind of access you use doesn't matter, sometimes it's just a matter of taste. These expressions are equivalent, actually p[i] is syntactic sugar for *(p + i):
*(*(matrix + i) + j)
matrix[i][j]
Note 1: As some commenters already recommend, you should raise the warning level to the maximum and correct the source until all diagnostics are handled.
Note 2: When your arrays vary in their dimensional sizes you need to think of a way to tell these sizes to your function.

3d dimensional array with malloc and calloc?

I am trying to make an arrangement with dynamic memory, 3-dimensional, my code is as follows:
typedef unsigned char matrix;
matrix ***mat(int n, int b)
{
matrix ***temp = (matrix ***)malloc(n*sizeof(matrix**));
for(int i=0; i<n; i++)
{
temp[i] = (matrix **)malloc(b*sizeof(matrix *));
for(int j = 0; j < b; j++)
temp[i][j]= (matrix *)malloc(b*sizeof(matrix));
}
return temp;
}
int main()
{
matrix ***M2 = mat(3,2);
for(int i=0; i<3; i++)
{
for(int j=0; j<2; j++)
{
for(int k=0; k<2; k++)
{
printf(" %d", M2[i][j][k]);
}
printf("\n");
}
printf("\n");
}
return 0;
}
when I run the program I have a segment violation, someone can tell me what the error is, since I can not visualize
I guess in the most nested for loop (the j one) the variables are messed in declaration for(int j = 0; i < b; i++). Try j for all
Usually I will do this kind of thing in FORTRAN, personally I like write the algorithm involving high dimensional array in FORTRAN as a library, and do the flow control staff in C. While 3D is still easily manageable in C, you need really careful with the pointers, here is a working example, it's valgrind clean.
#include <stdio.h>
#include <stdlib.h>
float ***myarray(int l, int m, int n)
{
float **ptr = malloc(sizeof(float*)*(l+l*m));
float *data = malloc(sizeof(float)*l*m*n);
float **p1 = ptr, **p2 = ptr+l;
for(int i=0; i<l; i++) {
p1[i] = (float*)(p2+i*m);
for(int j=0; j<m; j++)
p2[i*m+j] = data+(i*m+j)*n;
}
return (float***)ptr;
}
void myfree(float ***a)
{
free(a[0][0]);
free(a);
}
int main()
{
float ***array = myarray(4,3,2);
for(int i=0; i<4; i++)
for(int j=0; j<3; j++)
for(int k=0; k<2; k++)
array[i][j][k] = i+j+k;
myfree(array);
return 0;
}
you must correct the j counter inside the nested for loop in mat function, this is the correct one:
for(int j = 0; j < b; j++)

Algorithms for deleting multiple elements in arrays in C

I am trying to learn C and I am trying to write a piece of code which does the following:
Take user input of a natural number n
Take user input of n elements and store them in the array x
Delete all negative numbers from the array x
Print the new array, with the length n - number of deleted elements
Here is my code:
#include <stdio.h>
int main(void)
{
int n, i, count=0;
double x[1000];
scanf("%d", &n);
for (i=0; i<n; i++)
scanf("%lg", &x[i]);
for (i=0; i<n; i++)
{
if (x[i] < 0)
{
count++;
continue;
};
x[i-count]=x[i];
};
n -= count;
for (i=0; i<n; i++)
printf("%d: %g\n", i, x[i]);
return 0;
}
I have been told that I should replace my second for loop with the following code:
int j=0
...
for (i=0; i<n; i++)
{
if (x[i] < 0)
{
count++;
continue;
};
if (i > j)
x[j] = x[i];
j++;
};
Could someone please explain why is the latter code better?
If i==j, then you're assigning an element to itself: not wrong, but a (small) waste of effort.
If you really want to improve this, avoid putting the negative values in the array in the first place.

Question regarding C loops

I'm not exactly sure why this isn't returning what it should be, perhaps one of you could help me out. I have the following for loop in C:
for (i=0; i<nrow; i++) {
dat[k]=l.0;
k++;
}
Now, you would think that this would set all values of dat (of which there are nrow values) to 1.0; Instead, it is being set to 0. The program compiles fine and everything goes smoothly. The memory is properly allocated and dat is defined as a double.
Is there a reason this is yielding 0? I'm guessing the 0 is coming from the initialization of the dat variable (since I used calloc for memory allocation, which supposedly initializes variables to 0 (but not always)).
EDIT: Please note that there is a specific reason (this is important) that I'm not defining it as dat[i]. Additionally. k was defined as an integer and was initialized to 0.
EDIT 2: Below is the entire code:
#include "stdio.h"
#include "stdlib.h"
#define NCH 81
// Generate swap-mode data for bonds for input.conf file
int main()
{
int i,j,k;
int **dat2;
double *dat;
int ns = 500;
int nrow = NCH*(ns-1);
dat = (double*) calloc(nrow, sizeof(double));
dat2 = (int**) calloc(nrow,sizeof(int*));
/*for (i=0; i<nrow; i++) {
dat2[i] = (int*) calloc(2, sizeof(int));
for (j=0; j<2; j++)
dat2[i][j] = 0;
}*/
k=0;
printf("\nBreakpoint\n");
/*for (i=0; i<81; i++) {
for (j=0; j<250; j++) {
dat[k] = j+1;
k++;
}
for (j=251; j>1; j++) {
dat[k] = j-1;
k++;
}
}*/
FILE *inp;
inp = fopen("input.out", "w");
for (i=0; i<nrow; i++) {
dat[k]=1.0;
k++;
}
//fprintf(inp, "%lf\n", dat[i]);
printf("%d", dat[nrow]);
printf("\nDone\n");
fclose(inp);
return 0;
}
Thanks!
Amit
printf("%d", dat[nrow]);
is not valid, because the nrow'th element of dat doesn't exist.
Are you sure you are starting 'k' at zero?
In the sample you posted you are using l not 1 - is this just a typo?
for (i=0; i<nrow; i++) {
dat[k]=1.0;
k++;
}
That should work.
Two things:
I'm assuming the l.0 is a type and your l is actually a 1.
Secondly, why are you using k in your for loop instead of using i? Try using this instead:
for (i=0; i<nrow; i++) {
dat[i]=1.0;
}
Either this works your compiler/hardware is bugged.
k = 0;
for (i=0; i < nrow; i++) {
dat[k++] = 1.0f;
}
printf("%d, %d", dat[0], dat[nrow - 1]);
when you printf("%d", dat[nrow]), dat[nrow] has not been set to 1. In the for loop the condition is i < nrow so it's before it. You need i <= nrow.

Resources