I am in the process of learning C. I have a method that takes 3 strings and combines them to do some operation. Following was my first implementation using a GCC compiler.
void foo(const char *p1, const char *p2, const char *p3)
{
size_t length = strlen(p1) + strlen(p2) + strlen(p3);
char combined[length + 1];
memset(combined, 0, length + 1);
strcat(combined, p1);
strcat(combined, p2);
strcat(combined, p3);
printf("Result : %s", combined);
}
int main()
{
foo("hello ", "world ", "how");
return 0;
}
This works well. But when I compiled this using, cc -Wall -pedantic -g foo.c -o foo
, I started getting warnings like ISO C90 forbids variable length array ‘combined’
. MSVC was not compiling this code. Changed the code like
void foo(const char *p1, const char *p2, const char *p3)
{
size_t length = strlen(p1) + strlen(p2) + strlen(p3);
char *combined = (char *) malloc(length + 1);
memset(combined, 0, length + 1);
strcat(combined, p1);
strcat(combined, p2);
strcat(combined, p3);
printf("Result : %s", combined);
free(combined);
}
Questions
-Wall -pedantic
. Should I use -ansi
too? What would be the equivalent flags available in MSVC?Functions for String Manipulation It's used to assess the length of a sequence - a list, tuple, etc. Since strings are lists, their length can also be assessed with the len() function! It takes any iterable sequence as an input and returns its length as an integer.
There are two types of methods in String : shared methods and instance methods.
In C++, a string is a sequence of characters. As you know, C++ does not support the built-in string type, and you have previously used null character-based terminated arrays to store and manipulate strings. These strings are termed C Strings. C++ often becomes inefficient at operating on strings.
This works well. But when I compiled this using, cc -Wall -pedantic -g foo.c -o foo, I started getting warnings like ISO C90 forbids variable length array ‘combined’.
Try compiling with -std=c99
option (gcc).
MSVC was not compiling this code. Changed the code like
If variable length arrays are not part of standard, why GCC implemented it?
VLAs are part of ISO C99(gcc and g++(as an extension) support VLAs). MSVC still only supports C89.
My code is expected to compile on GCC and MSVC.
Then you should not use VLAs in your code IMHO.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With