Thread: memory allocation ptr to array? how?

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

    memory allocation ptr to array? how?

    hi people,

    i am having some problems, perhaps understanding about how dynamic memory allocation works with pointers and arrays.

    Im trying to get the user to input the size of the string in my program and allocates a certain amount of memory to hold the string of the size.

    Next, i am going to ask the user to input a string which must consists of only M, U, I. Im going to put that into my input array.

    The problem now is how am i going to reference the memory pointer to the input array ?

    Also im having a problem with functions too. My isaMUstring function has to return a 1, if the user input correctly ( only M, U, I) and a 0 if otherwise. I can't seem to get the concept of getting the return value of the function to work in my main function.

    If i can get the the return value of my function, i am able to perform other task like if the function return a 1, i would print "Correct", if otherwise, i would print "Incorrect".

    I have tried

    if( isaMUstring( 1 ) ){

    do someting}

    in the main.

    but it doesn't work.

    Could someone offer some help on the above 2 problems?

    Below is a sample of my code.

    Thanks in advance.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int isaMUstring( const char *string );
    
    
    
    
    int main(){
    
    	int size;
    	char input[20];
    
    	char *ptr;
    
    
    	printf("Enter the size of string.");
    	scanf("%d",&size);
    
    	ptr = (char *)malloc((size +1) * sizeof(char *));
    
    	
    
    	if( ptr) {
    
    	printf("Enter a character string(consist of 'M', 'I', 'U' only) :\n");
    	scanf("%s",&input);
    
    
    	isaMUstring( input );
    
    	}
    
    	return 0;
    }
    
    int isaMUstring( const char *string ) {
    
    
    	const char *cha1 = "M";
    	const char *cha2 = "I";
    	const char *cha3 = "U";
    	int a;
    
    	a = 0;
    
    	if( strpbrk( string, cha1) != NULL) {
    		a += 1;
    	}
    	if( strpbrk( string, cha2) != NULL) {
    		a += 1;
    	}
    	if( strpbrk( string, cha3 ) != NULL) {
    		a += 1;
    	}
    
    	if( a == 3 ) {
    
    		printf("Correct\n");
    	}
    	else {
    		printf("Wrong\n");
    	}
    
    }
    cross posted in : http://www.daniweb.com/techtalkforum...381#post157381

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Code:
    ptr = (char *)malloc((size +1) * sizeof(char *));
    1) You don't need (read: shouldn't) typecast the return of malloc or it's kin in C ever. (Or any function that returns a void* for that matter.)
    2) You don't want the size you're allocating. You're allocating size +1 character pointers. I think you meant characters.
    3) You don't ever actually doing anything with ptr. At all. You don't free it, or anything. You just allocate it, test to see if malloc failed, and then don't do anything at all with it.

    ...

    4) You never actually return anything in your isaMUstring function. You also never actually check it's return value, so why not make it void? In fact, I don't really see any point for this function at all, since it doesn't do anything you're trying to do or use it for.
    5) Your "string" in isaMUstring will never return 3. You're testing to see if it exactly matches. You should be using something like strchr if you want to see if it contains a specific character, rather than trying to see if it exactly matches, character for character, another string.


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

  3. #3
    Registered User
    Join Date
    Aug 2005
    Posts
    7
    Quote Originally Posted by quzah
    Code:
    ptr = (char *)malloc((size +1) * sizeof(char *));
    1) You don't need (read: shouldn't) typecast the return of malloc or it's kin in C ever. (Or any function that returns a void* for that matter.)
    2) You don't want the size you're allocating. You're allocating size +1 character pointers. I think you meant characters.
    3) You don't ever actually doing anything with ptr. At all. You don't free it, or anything. You just allocate it, test to see if malloc failed, and then don't do anything at all with it.

    ...

    4) You never actually return anything in your isaMUstring function. You also never actually check it's return value, so why not make it void? In fact, I don't really see any point for this function at all, since it doesn't do anything you're trying to do or use it for.
    5) Your "string" in isaMUstring will never return 3. You're testing to see if it exactly matches. You should be using something like strchr if you want to see if it contains a specific character, rather than trying to see if it exactly matches, character for character, another string.


    Quzah.
    1) yeah i agree with u quzah, seems dumb of me to allocate memory to a ptr i don't use.

    the idea is i want to ask for the size of the string from the user, and
    allocate the memory of that size to the next user input array....

    would it be fine if i do something like this?

    Code:
    int main(){
    
    	int size;
    	char input[20];
    
    	const char *string;
    
    
    	printf("Enter the size of string.");
    	scanf("%d",&size);
    
    	string = (char *)malloc((size +1) * sizeof(char *));
    
    
    
    	if( string ) {
    
    	printf("Enter a character string(consist of 'M', 'I', 'U' only) :\n");
    	scanf("%s",&input);
    
    
    	isaMUstring( input );
    
    	}
    
    	return 0;
    }
    
    int isaMUstring( const char *string ) {
    
    
    	const char *cha1 = "M";
    	const char *cha2 = "I";
    	const char *cha3 = "U";
    	int a;
    
    	a = 0;
    
    	if( strpbrk( string, cha1) != NULL) {
    		a += 1;
    	}
    	if( strpbrk( string, cha2) != NULL) {
    		a += 1;
    	}
    	if( strpbrk( string, cha3 ) != NULL) {
    		a += 1;
    	}
    
    	if( a == 3 ) {
    
    		printf("Correct\n");
    	}
    	else {
    		printf("Wrong\n");
    	}
    	
    	free( string );
    4 ) for isaMUstring function.

    i don't want to make it void because i want the function to return 1 or 0...

    but i can't get my main function to execute a task from the function return value...

    could you provide me with a example or link i can follow to?

    my analogy is as follows:

    int isaMUstring( const char *string) {

    do some algorithm;

    if(blarblar){
    return 1;
    }else {
    return 0;
    }
    }

    in my main function :

    i would get the return value from my isaMUstring function, and excute some tasks.

    something like

    if( isaMUstring( 'something in here i don't get) ) {
    do some tasks;
    }

    should i put a '1' in 'something in here i don't get' or??
    Last edited by kokopo2; 08-31-2005 at 05:11 AM.

  4. #4
    Nonconformist Narf's Avatar
    Join Date
    Aug 2005
    Posts
    174
    the idea is i want to ask for the size of the string from the user
    How does the user know what size the string is? It would be better to let them do whatever they want--they will anyway--and use a dynamically growing string that returns its length to you:
    Code:
    /*
      I'm pretty sure this works for all common 
      cases, but it's a quicky, so use at your own risk.
    */
    char *dfgets(FILE *stream, int *length) {
      char *t, *rs = NULL;
      int size = 0;
      int ch;
    
      *length = 0;
    
      while ((ch = fgetc(stream)) != EOF) {
        if (*length == size) { /* Resize string */
          size += 5;
          t = realloc(rs, size + 1);
          if (t == NULL) break;
          rs = t;
        }
    
        rs[(*length)++] = (char)ch;
    
        if (ch == '\n') break; /* Keep the newline */
      }
    
      if (*length == 0) return NULL;
    
      rs[*length] = '\0';
    
      /* Shrink-wrap the string */
      t = realloc(rs, *length + 1);
      if (t != NULL)
        rs = t;
    
      return rs;
    }
    should i put a '1' in 'something in here i don't get' or??
    Just compare it:
    Code:
    if(isaMUstring(somestring) == 1) {
      some stuff
    }
    else {
      other stuff
    }
    Just because I don't care doesn't mean I don't understand.

  5. #5
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    I wrote a function just like that earlier today. But I thought it might not work if realloc had to move the block of memory. When realloc moves the pointer, does it copy the data, too? Or what?

    And . . . length can be a local variable, since the calling function can figure out the length by using strlen(). The calling function has to free the string, but that can't really be avoided.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  6. #6
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Code:
    	const char *cha1 = "M";
    	const char *cha2 = "I";
    	const char *cha3 = "U";
    	int a;
    
    	a = 0;
    
    	if( strpbrk( string, cha1) != NULL) {
    		a += 1;
    	}
    	if( strpbrk( string, cha2) != NULL) {
    		a += 1;
    	}
    	if( strpbrk( string, cha3 ) != NULL) {
    		a += 1;
    	}
    (a += 1 can be a++.) What are you trying to do here? Search string for a character that isn't M, I, or U? If so, try this:

    Code:
        if(strspn(string, "MIU") != string+strlen(string)) {
            /* contains a char that isn't an M, I, or U */
        }
        else {
            /* contains only Ms, Is, and/or Us */
        }
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  7. #7
    Nonconformist Narf's Avatar
    Join Date
    Aug 2005
    Posts
    174
    When realloc moves the pointer, does it copy the data, too?
    Ya it does, realloc() would be worthless if it didn't because you never know when a different block is allocated.
    And . . . length can be a local variable, since the calling function can figure out the length by using strlen().
    It's faster to save the length than to keep calling strlen(). If the function gives you the length then there's no need to call strlen() at all.
    Just because I don't care doesn't mean I don't understand.

  8. #8
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    you never know when a different block is allocated [with realloc()]
    Of course you do . . . compare the return value and the first argument. But thanks, good thing it does.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  9. #9
    Nonconformist Narf's Avatar
    Join Date
    Aug 2005
    Posts
    174
    Of course you do . . . compare the return value and the first argument.
    I meant you don't have any control over it...
    Just because I don't care doesn't mean I don't understand.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 07-11-2008, 07:39 AM
  2. question about multidimensional arrays
    By richdb in forum C Programming
    Replies: 22
    Last Post: 02-26-2006, 09:51 AM
  3. Merge sort please
    By vasanth in forum C Programming
    Replies: 2
    Last Post: 11-09-2003, 12:09 PM
  4. Creating 2D arrays on heap
    By sundeeptuteja in forum C++ Programming
    Replies: 6
    Last Post: 08-16-2002, 11:44 AM
  5. Hi, could someone help me with arrays?
    By goodn in forum C Programming
    Replies: 20
    Last Post: 10-18-2001, 09:48 AM