473,462 Members | 1,333 Online
Bytes | Software Development & Data Engineering Community
Create 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 3094
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.net --
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.invalidwrote:
<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.net --
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.invalidwrote:
<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.net --
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.invalidwrote:

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.net --
Jul 22 '08 #8
rahul said:
On Mon, 21 Jul 2008 19:25:12 +0530, Richard Heathfield
<rj*@see.sig.invalidwrote:

>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)*CHAR_BIT)/log2(n) digits.
Adding one for the - and one for the terminator gives us the
floating-point expression 1 + 1 + (sizeof(int)*CHAR_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(int)*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.invalidwrote:

<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.net --
Jul 22 '08 #10
rahul wrote:
That looks slick. Better than calling realloc/malloc(which makes system
calls to underlying OS on most of the platforms; quiet expansive)
Doesn't one /want/ (many) realloc calls to be quietly expansive?

--
'It changed the future .. and it changed us.' /Babylon 5/

Hewlett-Packard Limited Cain Road, Bracknell, registered
no:
registered office: Berks RG12 1HN 690597
England

Jul 22 '08 #11
On Tue, 22 Jul 2008 17:34:24 +0530, Chris Dollin <ch**********@hp.com>
wrote:

>
Doesn't one /want/ (many) realloc calls to be quietly expansive?
That looks slick. Better than calling realloc/malloc(which makes system
calls to underlying OS on most of the platforms; QUITE expansive)

-- Posted on news://freenews.netfront.net - Complaints to ne**@netfront.net --
Jul 22 '08 #12
On Tue, 22 Jul 2008 17:34:24 +0530, Chris Dollin <ch**********@hp.com>
wrote:
rahul wrote:
>That looks slick. Better than calling realloc/malloc(which makes system
calls to underlying OS on most of the platforms; quiet expansive)

Doesn't one /want/ (many) realloc calls to be quietly expansive?
QUITE EXPENSIVE (before you correct my other misspelling)
-- Posted on news://freenews.netfront.net - Complaints to ne**@netfront.net --
Jul 22 '08 #13

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

Similar topics

3
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...
3
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...
10
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
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...
4
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
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...
0
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...
3
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...
10
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...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
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...
0
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,...
0
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...
0
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...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.