Skip to content

Instantly share code, notes, and snippets.

@manodeep
Created May 18, 2019 01:42
Show Gist options
  • Save manodeep/0a315422d741a44eb867221f70ae8dd0 to your computer and use it in GitHub Desktop.
Save manodeep/0a315422d741a44eb867221f70ae8dd0 to your computer and use it in GitHub Desktop.
Passing strings to functions
## compiled with gcc -Wall -std=c99 xx.c -o xx -Wextra
## and then run. Produces the following output:
Printing mystring_fixed...
In print_string_fixed_len_array> string = `Fixed len array with (50) elements'
In print_string_pointer> string = `Fixed len array with (50) elements'
Printing mystring_fixed......done
Printing mystring...
In print_string_fixed_len_array> string = `Fixed (unspecified) length array'
In print_string_pointer> string = `Fixed (unspecified) length array'
Printing mystring......done
Printing allocatedstring...
In print_string_fixed_len_array> string = `Allocated len array with 50 elements'
In print_string_pointer> string = `Allocated len array with 50 elements'
Printing allocatedstring......done
#include <stdio.h>
#include <stdlib.h>
#define STR_HELPER(x) #x
#define STR(x) STR_HELPER(x)
#define FIXEDLEN (50)
void print_string_fixed_len_array(char mystring[FIXEDLEN])
{
fprintf(stderr,"In %s> string = `%s'\n", __FUNCTION__, mystring);
}
void print_string_pointer(char *mystring)
{
fprintf(stderr,"In %s> string = `%s'\n", __FUNCTION__, mystring);
}
int main(int argc, char **argv)
{
char mystring_fixed[FIXEDLEN] = "Fixed len array with " STR(FIXEDLEN) " elements";
char mystring[] = "Fixed (unspecified) length array";
char *allocatedstring = malloc(FIXEDLEN*sizeof(char));
if(allocatedstring == NULL) {
fprintf(stderr,"Error: Could not allocate memory for %d bytes\n", FIXEDLEN);
return EXIT_FAILURE;
}
snprintf(allocatedstring, FIXEDLEN-1, "Allocated len array with %d elements", FIXEDLEN);
fprintf(stderr,"Printing mystring_fixed...\n");
print_string_fixed_len_array(mystring_fixed);
print_string_pointer((char *) &mystring_fixed);
fprintf(stderr,"Printing mystring_fixed......done\n\n");
fprintf(stderr,"Printing mystring...\n");
print_string_fixed_len_array(mystring);
print_string_pointer((char *) &mystring);
fprintf(stderr,"Printing mystring......done\n\n");
fprintf(stderr,"Printing allocatedstring...\n");
print_string_fixed_len_array(allocatedstring);
print_string_pointer(allocatedstring);
fprintf(stderr,"Printing allocatedstring......done\n\n");
free(allocatedstring);
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment