473,569 Members | 2,762 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to concatenate Matrix's elements ?

Hi all,
Is there any way to print a matrix's elements using a simple printf ?
what I want as result is for example:
if mat ={0,1,2,3}
result must be: "0123".

I tried this code:

/*************** *************** *************** *************** ***/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define size 10

int main (void)
{
// Declaration
int i = 0;
int mat[size]= {0,0,0,0};
char convert[size]= {0,0,0,0};

for (i=0;i<4;i++)
{
mat[i]=mat[i]+i+1;
printf("mat[%d]=%d\n",i,mat[i]);

// Convert int to string
sprintf(convert ,"%s",(char *)&mat[i]);
// concatenate matrix's elements
// strcat(convert[i+1],convert[i]);

}

printf ("Matrix is equal to %s\n",(char *)&convert);

return (0);
}

/*************** *************** *************** *************** ***/

After execution I get this
$ ./matrix
mat[0]=1
mat[1]=2
mat[2]=3
mat[3]=4
Matrix is equal to 

If I activate the line :
strcat(convert[i+1],convert[i]);
I get
matrix.c: In function ‘main’:
matrix.c:23: warning: passing argument 1 of ‘strcat’ makes pointer
from integer without a cast
matrix.c:23: warning: passing argument 2 of ‘strcat’ makes pointer
from integer without a cast

And when executing :
./matrix
mat[0]=1
Segmentation fault.
Jul 21 '08 #1
12 3107
Nezhate said:
Hi all,
Is there any way to print a matrix's elements using a simple printf ?
Yes.
what I want as result is for example:
if mat ={0,1,2,3}
result must be: "0123".
#include <stdio.h>

int main(void)
{
int mat = { 0, 1, 2, 3, };
size_t len = sizeof mat / sizeof mat[0];
size_t idx = 0;
while(idx < len)
{
printf("%d", mat[idx++]);
}
putchar('\n');
return 0;
}

--
Richard Heathfield <http://www.cpax.org.uk >
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Jul 21 '08 #2
On Mon, 21 Jul 2008 15:49:51 +0530, Nezhate <ma************ @gmail.com>
wrote:

int mat[size]= {0,0,0,0};
char convert[size]= {0,0,0,0};
Since it looks like you want the output as string, you need to have size +
1 elements (for the \0). If you want the aggregate to be initialize to 0,
this would suffice:
int mat[size] = {0};
char convert[size] = "";
Start with an empty string.

for (i=0;i<4;i++)
Why do you think you declared SIZE? (Don't use magic numbers)

sprintf(convert ,"%s",(char *)&mat[i]);
mat[i] is an int. &mat[i] is pointer to an int. You are casting it to char
* and asking sprintf to assume it is a string(null-terminated array of
characters).

// concatenate matrix's elements
// strcat(convert[i+1],convert[i]);
convert[i+1] is a character; so is convert[i]. strcat requires char * and
const char *.
strcat after sprintf? Your logic is convoluted.

No wonder your code is not working.

#include <stdio.h>
#include <string.h>

#define SIZE 4

int
main (void) {
int mat[SIZE] = {0, 1, 2, 3};
char convert[SIZE + 1];
int count;
for (count = 1; count < SIZE; count++) {
sprintf (convert + count, "%d", mat[count]);
}

printf ("The matrix is %s\n", convert);
return 0;
}



--
Nothing worth having comes easy.

-- Posted on news://freenews.netfront.net - Complaints to ne**@netfront.n et --
Jul 21 '08 #3
rahul said:

<snip>
No wonder your code is not working.
Likewise.
#include <stdio.h>
#include <string.h>

#define SIZE 4

int
main (void) {
int mat[SIZE] = {0, 1, 2, 3};
char convert[SIZE + 1];
int count;
for (count = 1; count < SIZE; count++) {
sprintf (convert + count, "%d", mat[count]);
This fails to deal with mat[0], and leaves an indeterminate value in
convert[0], which means that...
}

printf ("The matrix is %s\n", convert);
....this print invokes undefined behaviour.

That bug is easy to fix, but what if mat[1] were a two-digit number rather
than a one-digit number? Your code would not withstand even such a slight
change in data.

--
Richard Heathfield <http://www.cpax.org.uk >
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Jul 21 '08 #4
On Mon, 21 Jul 2008 16:51:39 +0530, Richard Heathfield
<rj*@see.sig.in validwrote:
<snip>

#include <stdio.h>
#include <string.h>

#define SIZE 4
#define BUFSIZE 100
int
main (void) {
int mat[SIZE] = {0, 11, 222, 3333};
char convert[BUFSIZE];
int count = 0;
int index = 0;

for (; count < SIZE; count++) {
index += sprintf (convert + index, "%d", mat[count]);
}
conunt[index] = '\0';
printf ("The matrix is %s\n", convert);
return 0;
}

Still the buffer can overflow.
--
Nothing worth having comes easy.

-- Posted on news://freenews.netfront.net - Complaints to ne**@netfront.n et --
Jul 21 '08 #5
On Mon, 21 Jul 2008 17:11:19 +0530, rahul <ra***@nowhere. comwrote:
On Mon, 21 Jul 2008 16:51:39 +0530, Richard Heathfield
<rj*@see.sig.in validwrote:
<snip>

#include <stdio.h>
#include <string.h>

#define SIZE 4
#define BUFSIZE 100
int
main (void) {
int mat[SIZE] = {0, 11, 222, 3333};
char convert[BUFSIZE];
int count = 0;
int index = 0;

for (; count < SIZE; count++) {
index += sprintf (convert + index, "%d", mat[count]);
}
conunt[index] = '\0';
oops; that is convert[index]. (There may be other typos:))
>

printf ("The matrix is %s\n", convert);
return 0;
}

Still the buffer can overflow.


--
Nothing worth having comes easy.

-- Posted on news://freenews.netfront.net - Complaints to ne**@netfront.n et --
Jul 21 '08 #6
rahul said:

<snip>
#include <stdio.h>
#include <string.h>

#define SIZE 4
#define BUFSIZE 100
int
main (void) {
int mat[SIZE] = {0, 11, 222, 3333};
char convert[BUFSIZE];
int count = 0;
int index = 0;

for (; count < SIZE; count++) {
index += sprintf (convert + index, "%d", mat[count]);
}
conunt[index] = '\0';
printf ("The matrix is %s\n", convert);
return 0;
}

Still the buffer can overflow.
Right (or at least, it will be able to, after you fix the typo) - which is
why I'm at a loss as to why you continue to recommend this approach.
--
Richard Heathfield <http://www.cpax.org.uk >
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Jul 21 '08 #7
On Mon, 21 Jul 2008 19:25:12 +0530, Richard Heathfield
<rj*@see.sig.in validwrote:

Right (or at least, it will be able to, after you fix the typo) - which
is
why I'm at a loss as to why you continue to recommend this approach.
I assumed that the OP wants an array of int to be converted to string. We
don't have anything that tells us maximum number of digits possible in int
data type. Had there been something like INT_DIG_MAX, we could have
declared the convert of right size:

#define SIZE 4
#define BUFSIZE (SIZE * INT_DIG_MAX + 1)

In absence of such a defined constant, the other approach could be to keep
track of index.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define SIZE 4
#define BUFSIZE 100
#define INT_DIG 50 /*assuming an int is not going to have more than 50
digits */
#define FUZZ_FACTOR 20

int
main (void) {
int mat[SIZE] = {0, 11, 222, 3333};
char *convert = malloc(BUFSIZE) ;
char temp[INT_DIG];
int count = 0;
int index = 0;
int ret = 0;
int tempIndex = 0;

for (; count < SIZE; count++) {
ret = sprintf (temp, "%d", mat[count]);
tempIndex = index + ret;
if ( tempIndex >= BUFSIZE ) {
convert = realloc(convert , tempIndex + FUZZ_FACTOR);
if (NULL == convert) {
exit (EXIT_FAILURE);
}
}
index += sprintf (convert + index, "%d", mat[count]);
}

conunt[index] = '\0';

printf ("The matrix is %s\n", convert);
return 0;
}
This whole stuff is convoluted but works.


-- Posted on news://freenews.netfront.net - Complaints to ne**@netfront.n et --
Jul 22 '08 #8
rahul said:
On Mon, 21 Jul 2008 19:25:12 +0530, Richard Heathfield
<rj*@see.sig.in validwrote:

>Right (or at least, it will be able to, after you fix the typo) - which
is
why I'm at a loss as to why you continue to recommend this approach.
I assumed that the OP wants an array of int to be converted to string. We
don't have anything that tells us maximum number of digits possible in
int data type.
But we do! (We must, however, not forget that "digits" are a representation
issue, not a property of the type itself.)

For example, if we want a base-1 "tally" representation (clumsy, but
doable), then on a system with, say, 19-bit ints, we know that there will
be no more than 2^(19 - 1) = 262144 digits (all 1s!), and perhaps a
leading minus sign.

Considering only positional systems now (and indeed positional systems with
integral number bases >= 2!), we can derive a general formula for the
maximum number of digits an int can store, and arrange it so that, whilst
we might overestimate a little, we will never underestimate (i.e. we adopt
a conservative attitude).

First, we need the maximum number of bits used in an int. We know that an
int has sizeof(int) bytes (including any padding bits, if applicable), and
we know that a byte has CHAR_BIT bits, so our int can't have more than
sizeof(int) * CHAR_BIT bits in it.

This gives us our first expression:

sizeof(int) * CHAR_BIT

Our worst case for positional systems is base Two, because every bit will
require its own position. In base n, we need log2(n) bits per digit, so an
int can represent no more than (sizeof(int)*CH AR_BIT)/log2(n) digits.
Adding one for the - and one for the terminator gives us the
floating-point expression 1 + 1 + (sizeof(int)*CH AR_BIT) / log2(n) where
log2() might look something like this:

double log2(double x)
{
return log(x) / log(2);
}

Not very convenient, is it? We would prefer a constant integer expression,
right? Well, we can have one, if we are prepared to do a little
pre-calculation for bases that we're particularly interested in. For
example, for base Ten, log2(n) is around 3.32193. This means that, given b
bits of data, every 3.32193+ of them needs a separate character in the
output string for a digit, so we need 1+1+((sizeof(in t)*CHAR_BIT)/3.32193)
characters. Conservatively, 1 + 1 + (sizeof(int) * CHAR_BIT) / 3 would do
it, if it weren't for the fact that integer division is so aggressive.
We'd like to round UP to the next size if need be, rather than down, so we
add 2 to the dividend, giving us 1 + 1 + ((sizeof(int) * CHAR_BIT + 2)/3

This is an integer constant expression, so it can be used in C90 array
definitions:

/* define an array long enough to hold a base-ten representation of a
string, including one for the sign and one for the null */
char textrep[1 + 1 + ((sizeof(int) * CHAR_BIT + 2) / 3] = {0};

Here are the divisors you need for various bases:

base divisor
2 1
3-7 2
8-15 3
16-31 4
32-63 5
64-127 6

The pattern is clear. If you're using number bases higher than 127, you are
likely to run into glyph issues unless you're using Unicode or something,
so I've stopped the table there.

--
Richard Heathfield <http://www.cpax.org.uk >
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Jul 22 '08 #9
On Tue, 22 Jul 2008 13:26:31 +0530, Richard Heathfield
<rj*@see.sig.in validwrote:

<snip>

That looks slick. Better than calling realloc/malloc(which makes system
calls to underlying OS on most of the platforms; quiet expansive)

-- Posted on news://freenews.netfront.net - Complaints to ne**@netfront.n et --
Jul 22 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
12885
by: robix | last post by:
Hi again. I'm now asking your help because of a smal problem i'm getting with my multiplication matrix code. I'll try to give you as many details as possible. My matrix structure: typedef struct { int col; /* number of colowns */ int lin; /* number of lines*/
3
7124
by: Jack Middleton | last post by:
Hi! I'm lookin for a faster permutation algorithm for matrices. I know that it can be done with multiplying a matrix with a permutation matrix. It just seems a waste to iterate through all those zeroes. Is there an algorithm for matrixes that is optimized just for permutations? The matrices that I use are fairly small (around 6*6) and I...
10
8703
by: Duncan M Gunn | last post by:
Hi, I need to store the following matrix of values: T U V A 2 1 1 B 2 - - C - - 2 Where (-) is an empty cell.
4
2199
by: L. | last post by:
Hello, I need to generate random Matrices (say of size 5*5), each with an average of X (say X=0.5), but with different values’ range. One matrix should have values in the range of 0-1, while the second one’s values should have a low variance and lie in the range of (X-1) – (X+1). The matrices represent a visual scene and the values...
4
7633
by: deLenn | last post by:
Hi, Does scipy have an equivalent to Matlab's 'find' function, to list the indices of all nonzero elements in a sparse matrix? Cheers.
2
8552
by: DarrenWeber | last post by:
Below is a module (matrix.py) with a class to implement some basic matrix operations on a 2D list. Some things puzzle me about the best way to do this (please don't refer to scipy, numpy and numeric because this is a personal programming exercise for me in creating an operational class in pure python for some *basic* matrix operations). 1....
0
2798
by: DarrenWeber | last post by:
# Copyright (C) 2007 Darren Lee Weber # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it...
3
4996
by: LolaT | last post by:
I am making a program that deals with matrices in Java. I keep getting an error and I don't know how to fix it my code so far is import java.io.*; import java.util.*; import java.util.Scanner;
10
5406
by: Babak | last post by:
Hi, I've developed a C program which contains a large number of vectors and matrices operations. Throughout my code, I used the template from the Numerical Recipes book to define vectors and matrices and access their elements. For example, to define a vector I used the function: my_vector=vector(0,n-1); Which actually allocate the...
0
7694
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7609
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
1
7666
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7964
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6278
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5504
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3651
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3636
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
936
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.