Advertisement
thatguyandrew1992

C - Return a new array via pointer

Feb 23rd, 2014
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.71 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4.  
  5. char *newChar();
  6.  
  7. int main(){
  8.    
  9.     //This will print what is returned from *newChar() - Just for testing to see if it works :)
  10.     printf("\n%s", newChar());
  11.    
  12.    
  13.     char *b = malloc(3 * sizeof(char)); //This is the local var - Must use malloc for this to work - The "3" is the size of the char array
  14.     b = newChar(); //This sets the local var to the return of *newChar()
  15.     printf("\n%s", b); //Print out
  16.    
  17. }
  18.  
  19. //This will return a pointer
  20. char *newChar(){
  21.  
  22.     char *a = malloc(3 * sizeof(char));
  23.    
  24.     a[0] = 'a';
  25.     a[1] = 'b';
  26.     a[2] = '\0';
  27.  
  28.     return a; //Since "a" was declared as a pointer, this is returning a pointer. Doing *a, would be the pointer of the pointer
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement