I have the following declaration:where size has a predefined value. I don't want to fix the size of the Array. I want to know how to declare a string which will hold a name with dynamic lenth in C.Code:char name[size + 1] = {'\0'};
Thank you.
I have the following declaration:where size has a predefined value. I don't want to fix the size of the Array. I want to know how to declare a string which will hold a name with dynamic lenth in C.Code:char name[size + 1] = {'\0'};
Thank you.
When do you know the length of the string you want to store?
At some point beforehand, you need to know the length, be it
size_t size = strlen(s);
char name[size+1];
strcpy(name,s);
or
size_t size = strlen(s);
char *name = malloc(size+1);
strcpy(name,s);
What is the lifetime of the string once you've stored it?
Your VLA cannot be returned from the current scope for example.
Also, VLA's can blow the stack without warning, whereas malloc will always return a status that allows you to recover gracefully.
There is no such thing in C as being able to declare
string name;
and then be able to retrieve arbitrary length input from some source without any further work on your part.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
I have a variable 'typeName' and a variable 'Name'. The varaibale 'Name' stores a string of characters in the following Format: Auto_'typeName'_Workflow. The string 'typeName' is determined at run time.
Code:char built_name[name_size + 1] = {'\0'}; sprintf(name, "Auto_%s_Workflow", typeName);
So name_size is just
strlen(typeName) + strlen("Auto__Workflow");
You could use the non-standard function asprintf(3): print to allocated string - Linux man page
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.