How to concatenate Matrix's elements ?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Nezhate

    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.
  • Richard Heathfield

    #2
    Re: How to concatenate Matrix's elements ?

    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

    Comment

    • rahul

      #3
      Re: How to concatenate Matrix's elements ?

      On Mon, 21 Jul 2008 15:49:51 +0530, Nezhate <mazouz.nezhate @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 news@netfront.n et --

      Comment

      • Richard Heathfield

        #4
        Re: How to concatenate Matrix's elements ?

        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

        Comment

        • rahul

          #5
          Re: How to concatenate Matrix's elements ?

          On Mon, 21 Jul 2008 16:51:39 +0530, Richard Heathfield
          <rjh@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 news@netfront.n et --

          Comment

          • rahul

            #6
            Re: How to concatenate Matrix's elements ?

            On Mon, 21 Jul 2008 17:11:19 +0530, rahul <rahul@nowhere. comwrote:
            On Mon, 21 Jul 2008 16:51:39 +0530, Richard Heathfield
            <rjh@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 news@netfront.n et --

            Comment

            • Richard Heathfield

              #7
              Re: How to concatenate Matrix's elements ?

              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

              Comment

              • rahul

                #8
                Re: How to concatenate Matrix's elements ?

                On Mon, 21 Jul 2008 19:25:12 +0530, Richard Heathfield
                <rjh@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 news@netfront.n et --

                Comment

                • Richard Heathfield

                  #9
                  Re: How to concatenate Matrix's elements ?

                  rahul said:
                  On Mon, 21 Jul 2008 19:25:12 +0530, Richard Heathfield
                  <rjh@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

                  Comment

                  • rahul

                    #10
                    Re: How to concatenate Matrix's elements ?

                    On Tue, 22 Jul 2008 13:26:31 +0530, Richard Heathfield
                    <rjh@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 news@netfront.n et --

                    Comment

                    • Chris Dollin

                      #11
                      Re: How to concatenate Matrix's elements ?

                      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

                      Comment

                      • rahul

                        #12
                        Re: How to concatenate Matrix's elements ?

                        On Tue, 22 Jul 2008 17:34:24 +0530, Chris Dollin <chris.dollin@h p.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 news@netfront.n et --

                        Comment

                        • rahul

                          #13
                          Re: How to concatenate Matrix's elements ?

                          On Tue, 22 Jul 2008 17:34:24 +0530, Chris Dollin <chris.dollin@h p.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 news@netfront.n et --

                          Comment

                          Working...