1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
// DECLARING and USING STRINGS on STACK
// A function can take a char array (e.g., char s[] = "…") but the rules are dicey.
// This works but some might not. Just use a char* when you want a function to take
// a string as a parameter.
static void _print_string(char s[], int x) {
printf("%s\n", s);
printf("x == %d\n", x);
}
// static char[] _get_abc() { // GCC ERROR: "expected identifier or ‘(’ before ‘[’ token"
// return "ABC";
//}
//static char _get_abc()[] { // GCC ERROR: "‘_get_abc’ declared as function returning an array"
// return "ABC";
//}
// If you need to return a string from a function, you must return a char*.
// (Don't try this on HW05. The bugs will be painful if you do.)
static char* _get_abc() {
return "ABC";
}
int main(int argc, char* argv[]) {
// String on the STACK
char s1[] = "ABC"; // array of size 4 (including null terminator '\0')
printf("s1 == \"%s\"\n", s1);
// Characters within a string on the stack and be modified.
s1[0] = 'E';
s1[1] = 'F';
s1[2] = 'G';
printf("s1 == \"%s\"\n", s1);
// WARNING: You cannot assign a whole array to another whole array (i.e., s2 = s1;)
char s2[] = "XYZ";
printf("s2 == \"%s\"\n", s2);
// s2 = s1; // GCC ERROR: "assignment to expression with array type"
_print_string(s2, 999);
char* s3 = _get_abc();
return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */
|
© Copyright 2022 Alexander J. Quinn This content is protected and may not be shared, uploaded, or distributed.