Thread: Array of Ints to a Strings

  1. #1
    Registered User
    Join Date
    Aug 2006
    Posts
    7

    Array of Ints to a Strings

    Most of my experience has been in MATLAB in alg development and system simulation and as such I have limited experience in handling types and memory (which MATLAB looks after for me)

    I'm now in the process of programming networked wireless microcontrollers which will feed data into MATLAB (this part works).

    I do need to run write come c to run on the microcontrollers and after going back to my c books im still not sure of the best approach.

    Code:
    int Neighbours[16];
    int count;
    
    --
    function runs which writes integers into the first "count" positions on Neighbours array.
    So now I have Neighbours with its first "count" postions filled and count advising me of how many positions were filled.
    I know the elements of Neighbours will be able to be represented by 4 digit decimal numbers.
    --
    
    I then want to place the 4 digit numbers in each position of Neighbours to a string seperated by comma.
    eg if neighbours[0] = 1600, neighbours[1] = 1601 and count = 2

    i need a string "1600,1601"

    Tips, ideas, directions to appropriate functions most appreciated!

    Matt

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    sprintf should be fine. There's a fun little variant you can do with strcat, sprintf and a pair of buffers, and a loop, but I'll let you see what you can come up with first.


    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Aug 2006
    Posts
    7
    Thank you for the tip

    I've come up with this toy code to see if it works and it does, however I not really sure if it should!

    When I used malloc i thought I should reserve enough space for the number of characters to go into my string. In this example I though this should be 14 (12*digits + 2* comma)

    I didn't expect the line
    Code:
    nPtr=(char*)malloc(3*sizeof(char));  //Space for 3 characters
    to work for 14 characters? Is it only working by luck or am i missing something?

    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main()
    {
    
            char *nPtr;
    	int a[] = {1021, 2034 ,3032, 4032, 5032 };
    
    	// Say I want to put the first three numbers into  string "1021,2034,3032"
    	
    	nPtr=(char*)malloc(3*sizeof(char));
    
    	sprintf(nPtr, "%d,%d,%d", a[0],a[1],a[2]);
    
    	printf("%s", nPtr);
    
    	return 0;
    }

  4. #4
    Devil's Advocate SlyMaelstrom's Avatar
    Join Date
    May 2004
    Location
    Out of scope
    Posts
    4,079
    Yes, that's luck. You're going out of your array bounds, but you didn't hit any other processes that would cause your program to crash. You'll have to fix that.

    Anyway, good work so far, now lets say the count was random, now. Let's see if you can figure out the, "strcat/sprintf looping" method that Quzah suggested.
    Sent from my iPadŽ

  5. #5
    Registered User
    Join Date
    Aug 2006
    Posts
    7
    Think I've got it, I had tried (and failed to get working) something a little similar prior to posting.

    This does work, any suggestions to make it better or cleaner would be appreciated.

    Code:
    int main(){
    
    	int neighbours[16] = { 1600, 1601, 1602, 1605, 1606, 1607 };	// Prepares for possibility of up to 16 neighbours
    	int i=0;	
    	int count;
    	const char *NILNB ="No Neighbours";
    	char *ONEMSG, *TEMP;
    	
    	count= 6; //ASNET_GetNeighbours(neighbours);
    
    	if(count==0) //Send an message to say no neighbours	
    		printf("%s", NILNB);
    				
    
    	ONEMSG =(char*)malloc(sizeof(char)*5*count);  // Enough for each 4 digit number + comma
    	
    TEMP =(char*)malloc(sizeof(char)*5);          // Enough for 4 digit number + comma
    		
    		sprintf(ONEMSG, "%d,", neighbours[i]);
    		i++;
    
    		while( count > i){
    			
    			sprintf(TEMP, "%d,", neighbours[i]);
    			strcat(ONEMSG, TEMP);
    			i++;
    		}
    	
    
    	printf("%s", ONEMSG);
    
    	return 0;
    }

  6. #6
    Devil's Advocate SlyMaelstrom's Avatar
    Join Date
    May 2004
    Location
    Out of scope
    Posts
    4,079
    Not bad, I had quickly written this up during the course of this topic:
    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main() {
        int neighbours[] = { 1600, 1620, 1640, 1660, 1680, 
                             1700, 1720, 1740, 1760, 1780 };
        short count = 3;
        char *strData = NULL;
        
        int i;
        for(i = 0; i < count; i++) {
           char buff[6]; // Four digits + ',' + '\0'
           sprintf(buff, "%d,",neighbours[i]); 
           strData = realloc(strData, ((strData == NULL ? 0 : strlen(strData)) + 
                                      strlen(buff)) * sizeof(char) + sizeof(char));
           /* Alright, that's the size of the main buffer + size of the new buffer + null character */
           if(strData == NULL) return 1;
           strcat(strData,buff);
        }
        strData[strlen(strData)-1] = '\0'; // The last extra comma
        
        printf("%s",strData);
        
        free(strData);
        return 0;
    }
    It's a bit neater with memory management but it's very similar to your result.

    EDIT: Ok, hopefully this is better, now. Although now the realloc statement is so contrived, I'm not even sure it it's efficient anymore.
    Last edited by SlyMaelstrom; 08-17-2006 at 01:19 AM.
    Sent from my iPadŽ

  7. #7
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    I'm shocked by the number of bugs in that code Sly.

    - Instant buffer overflow on buff
    - Very poor use of realloc
    - realloc doesn't expand in length, since you only take the length of buff (which doesn't count the \0 anyway), nevermind the current length of strData.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  8. #8
    Devil's Advocate SlyMaelstrom's Avatar
    Join Date
    May 2004
    Location
    Out of scope
    Posts
    4,079
    Ah, sorry. You're right, some numbers are a bit off... I'll fix that. I said elsewhere, I'm a bit tired.

    I don't know why it's poor use of realloc, other than the fact that the arguements are wrong, but perhaps you'd enlighten me? Maybe I should have casted the result?
    Last edited by SlyMaelstrom; 08-17-2006 at 12:31 AM.
    Sent from my iPadŽ

  9. #9
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Hint: What does realloc return when it fails?


    Quzah.
    Hope is the first step on the road to disappointment.

  10. #10
    Devil's Advocate SlyMaelstrom's Avatar
    Join Date
    May 2004
    Location
    Out of scope
    Posts
    4,079
    Alright, gotcha. Just like me to forget some error checking.

    In my defense, mattAU didn't error check, either.

    *waits for everyone to look the other way*
    *flees*
    Last edited by SlyMaelstrom; 08-17-2006 at 01:24 AM.
    Sent from my iPadŽ

  11. #11
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > EDIT: Ok, hopefully this is better, now
    Nope.

    > if(strData == NULL) return 1;
    If realloc returns NULL, the OLD memory you had is leaked away.

    > strcat(strData,buff);
    On the first allocation, there is no string to begin with (no \0), so the string could be copied anywhere.

    You didn't include stdlib either to prototype realloc.

    Maybe
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main() {
        int neighbours[] = { 1600, 1620, 1640, 1660, 1680,
                             1700, 1720, 1740, 1760, 1780 };
        size_t  count = 3; /* don't needlessly mix types */
        char    *strData = NULL;
        void    *temp;
        size_t  strLen = 0;
        size_t  i;
    
        for(i = 0; i < count; i++) {
            char   buff[100];  /* stop guessing about how many we need */
            size_t buffLen;
    
            sprintf(buff, "%d,",neighbours[i]);
            buffLen = strlen(buff);
    
            temp = realloc ( strData, (strLen + buffLen + 1) * sizeof *strData );
            if ( temp != NULL ) {
                strData = temp;
            } else {
                free( strData );
                return 1;
            }
            strcpy( &strData[strLen], buff );
            strLen += buffLen;
        }
    
        strData[strlen(strData)-1] = '\0'; /* The last extra comma */
        printf("%s\n",strData);
        free(strData);
    
        return 0;
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Swapping strings in an array of strings
    By dannyzimbabwe in forum C Programming
    Replies: 3
    Last Post: 03-03-2009, 12:28 PM
  2. Build an array of strings dynamically
    By Nazgulled in forum C Programming
    Replies: 29
    Last Post: 04-07-2007, 09:35 PM
  3. Array of strings in C
    By szill in forum C Programming
    Replies: 10
    Last Post: 02-22-2005, 05:03 PM
  4. printing an array of strings
    By linucksrox in forum C Programming
    Replies: 3
    Last Post: 05-11-2004, 03:31 PM
  5. remove strings from array
    By ipe in forum C Programming
    Replies: 2
    Last Post: 01-12-2003, 04:53 AM