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

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.

Related

Trash output in 8x8x2 array in C

I'm trying to represent a 8x8 Cartesian plane whose contents would be a string of length 2. I'd like to keep as type-safety as I can this scheme and doing this:
typedef char cartesian[8][8][2];
cartesian xy;
for(int i=0; i<8; i++){
for(int j=0; j<8; j++){
xy[i][j][0] = ' '
xy[i][j][1] = ' '
}
}
// The first element would represent some kind of information, and the other one
// would be just elements like '+' or '*'. In other cases, this would be 'EMPTY',
// it means a double space.
xy[2][4][0] = 'B';
xy[2][4][1] = '+';
// The right printing method (cause it doesn't have any trash) would be:
for(int i=0; i<8; i++){
for(int j=0; j<8; j++){
printf("| %c%c ", xy[i][j][0], xy[I][j][1] );
}
printf("|\n");
}
But here's the question: Why the output trash with printf("| %s ", xy[i][j][]); ?
I know this could be a dumb question, but I'm out and tired now.
Thanks in advance.
By the way, doesn't work to assign. I mean: xy[2][4][] = "B+";.
Here is your code rewritten. Note that cartesian is now [8][8][3] and strcpy is used to fill the last array dimension. For clarity, I moved to clearing on xy into a separate function.
#include <stdio.h>
#include <string.h>
typedef char cartesian[8][8][3];
void clearXY(cartesian *xy)
{
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
strcpy((*xy)[i][j], " ");
}
}
}
int main(int argc, char *argv[])
{
cartesian xy;
// The first element would represent some kind of information, and the other one
// would be just elements like '+' or '*'. In other cases, this would be 'EMPTY',
// it means a double space.
clearXY(&xy);
strcpy(xy[2][4], "B+");
printf("-------- Method 1 --------\n");
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
printf("| %c%c ", xy[i][j][0], xy[i][j][1]);
}
printf("|\n");
}
printf("-------- Method 2 --------\n");
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
printf("| %s ", xy[i][j]);
}
printf("|\n");
}
printf("-------- Done ------------\n");
}

C - one dimensional array 24 elements with random integers, use a loop. Then put into a two dimensional array of 6 x 4 elements

Write a program that declares a one-dimensional array of integers with 24 elements. Fill the array with random integers (use a loop). Neatly output each element in the one-dimensional array.
Next, convert your one-dimensional array of 24 elements into a two-dimensional array of 6 x 4 elements. Neatly output each element of the two-dimensional array. The values will be identical to the one-dimensional array – you’re just converting from one dimension to two.
My problem is every time I fix the first part of this, the second part doesn't work and vise versa.
Any advice will help, here's what I have now:
#include<stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROW 6
#define COL 4
#define NUM_ELEMENT 24
int main()
{
int myInts[NUM_ELEMENT];
int arr[ROW][COL], i, j;
srand((int)time(NULL));
for (i = 0; i < ROW; i++) {
for (j = 0; j < COL; j++) {
arr[i][j] = rand();
printf("%d ", arr[i][j]);
}
}
printf("\n2-D: \n\n");
for (i = 0; i < ROW; i++) {
for (j = 0; j < COL; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
return 0;
}
I GOT IT NOW, THANKS EVERYONE!!
This case is one of the few cases where pointer punning is acceptable.
#define ROW 6
#define COL 4
#define NUM_ELEMENT 24
int main()
{
int myInts[NUM_ELEMENT];
int (*arr)[ROW][COL], i, j;
for (i = 0; i < NUM_ELEMENT; i++)
{
myInts[i] = rand();
printf("%d \n", myInts[i]);
}
printf("\n2-D: \n\n");
arr = (int (*)[ROW][COL])myInts;
for (i = 0; i < ROW; i++)
{
for (j = 0; j < COL; j++)
{
printf("%d \t\t", (*arr)[i][j]);
}
printf("\n");
}
}
https://godbolt.org/z/STLp2r
Both arrays have to have the same memory representation and there are no alignment or aliasing issues.
You have missed statement to initialise (copy) value from myInt 1D array to arr 2D array:
Observe this code and get your code fixed
Int count = 0;
printf("\n2-D: \n\n");
for (i = 0; i < ROW; i++) {
for (j = 0; j < COL; j++) {
arr[i][j] = myInts[count++];
printf("%d ", arr[i][j]);
}
printf("\n");
}

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.

strange behaviour when printing a float and then an Array

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.

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