Initial assignment a Char Array using a Function in C - string

as we know it in C, a string defining is,
char string[] = "Hello World";
That is OK,
But I want to use a function and at initial same up,
I tried those, For example;
char * to_string()
{
return "Hello World";
}
Or;
char * to_String(void) // Function
{
char buff[16];
sprintf(buff, "%s", "Hello World");
return buff;
}
main() // main function
{
char Initial_String[] = to_String();
}
How to make this or any idea same another way.
I find what I dont send address of char Initial_String[] to fill into. No. is there Another method.
Thanks.

When you compile this, atleast in GCC, it will give you the following warning:
b.c:9: warning: function returns address of local variable
Why? Because buff[] is a local variable of function to_string(). Its scope is only inside the function to_string(). main() does not have any access to this variable. Try making buff[] a global variable instead.
Second problem: char Initial_String[] = to_String(); cannot be assigned value in this way. to_string() returns a char pointer, hence assign the value thus:
char *Initial_String = to_String();
The code below will work:
char buff[16];
char* to_String(void) // Function
{
//char buff[16]; /*this is a local variable*/
sprintf(buff, "%s", "Hello World");
return buff;
}
int main(void) // main function
{
char *Initial_String = to_String();
printf("%s", Initial_String);
return 0;
}

Yes You are right about local buffer mismake,
But This is not my wanting,
if I edit some differently,
char buff[16];
char* to_String(void) // Function
{
//char buff[16]; /*this is a local variable*/
sprintf(buff, "%s", "Hello World");
return buff;
}
int main(void) // main function
{
char *Initial_String_1 = to_String();
char *Initial_String_2 = to_String();
char *Initial_String_3 = to_String();
printf("%s", Initial_String_1 );
printf("%s", Initial_String_2 );
printf("%s", Initial_String_3 );
in this case, all strings will be same, because They have same buffer address,
I want to open the topic little more.
struct
{
long aaa;
short bbb;
int ccc;
char ddd;
.
.
. // the list goes on
}elements;
typedef struct
{
int lengt;
int *adress;
char name[10];
}_list;
char* to_String(long variable) // Function
{
sprintf(buff, "%ld", variable);
return buff;
}
int main (void)
{
_list My_List[] = {
{ sizeof(elements.aaa), &elements.aaa , to_string( elements.aaa) },
{ sizeof(elements.bbb), &elements.bbb , to_string( elements.bbb) },
{ sizeof(elements.ccc), &elements.ccc , to_string( elements.ddd) },
.
.
. //// the list goes on
};
I do not know, Do I make myself clear.
Here, string must be filled into name array, without assigning it the address.
I may have syntax mistake. the code is not tested with compiler. the idea is for illustrative purposes only.
I am trying to find a method for The purpose.
Thanks.

Related

Weird shapes as output( Strings)- C language

So i have a problem. I have to separate the first name, last name and hostname of email.
For example:
zephyr.extreme#gmail.com>> Input
Output=
First name= Zephyr
Last name= extreme
Host Name= gmail.com
I am not getting the desired result. I am getting some weird shapes as output.
Code:
#include <stdio.h>
int main()
{
char email[40], first[20],last[20],host[30];
printf("Enter the email= ");
gets(email);
int i;
while(email[i]!='\0')
{
while(email[i]!='.')
{
first[i]=email[i];
i++;
}
while(email[i]!='#')
{
last[i]=email[i];
i++;
}
while(email[i]!='\0')
{
host[i]=email[i];
i++;
}
}
puts(first);
puts(last);
puts(host);
}
Assuming the format will always be first.last#host..., use this code:
#include <stdio.h>
#include <string.h>
int main()
{
char email[40], first[20],last[20],host[30],name[40];
int firstDot,atSymbol;
int i;
int length;
char *token;
printf("Enter the email= ");
gets(email);
length = strlen(email);
for(i=0;i<length;i++){
if(email[i]=='.')
{
firstDot = i;
}
else if(email[i]=='#')
{
atSymbol = i;
}
}
strncpy(name,email,atSymbol);
name[atSymbol]= '\0';
token = strtok(name, ".");
/* walk through other tokens */
while( token != NULL )
{
printf( "%s\n", token );
token = strtok(NULL, ".");
}
strncpy(host,email+atSymbol,length-atSymbol);
host[length-atSymbol] = '\0';
puts(host);
}
So i updated the code, now the only problem is the last output.
After host name= gmail.com prints, but then some extra shapes are also printing. These are smile face and some weird symbols.
Code:
#include <stdio.h>
int main()
{
char email[40], first[20],last[20],host[30];
printf("Enter the email= ");
gets(email);
int i=0,j;
while(email[i]!='.')
{
first[i]=email[i];
i++;
}
i=0;
while(email[i]!='#')
{
last[i]=email[i];
i++;
}
j=i;
i=0;
while(email[j]!='\0')
{
host[i]=email[j];
j++;
i++;
}
printf("First Name= ");
puts(first);
printf("Last name= ");
puts(last);
printf("Host name= ");
puts(host);
}
C strings (char pointers) should be null-terminated. This means your string needs a '\0' character at its end so that string manipulation functions such as puts or strlen know where they end, in constrast to other languages where the string's length is stored together with it. The "weird shapes" you are seeing are just random data stored after the end of the string being interpreted as characters. When you call puts it just keeps outputting bytes-as-characters until it randomly finds a byte with value '\0'
You can solve this by adding a '\0' character to the end of the string after each of the blocks where you write a string.
while(email[i]!='.')
{
first[i]=email[i];
i++;
}
email[i] = '\0'; //same thing as email[i] = 0; but using a char makes what
//you're doing clearer

How to print n number of string in c?

#include<stdio.h>
#include<string.h>
#include<malloc.h>
int main()
{
char *name;
int a;
name=(char *)malloc(sizeof(name));
printf("no. of names:");
scanf("%d",&a);
int i;
for(i=0;i<a;i++)
{
printf("enter the names:");
scanf("%s",name);
}
for(i=0;i<a;i++)
{
printf("entered names are:%s\n",name);
}
return 0;
free(name);
}
how to print n numbers of entered string in c am already asked this question but i dont got any proper answer any body known the answer please edit my code please if you run my code its displays last string only i dont know why please help..
You need an array of names. To achieve what you are trying to do you can use either a static array with the maximum size or allocate the memory dinamically as in the following program.
Note that you should also test the return value of malloc... just in case.
#include<stdio.h>
#include<string.h>
#include<malloc.h>
int main()
{
char **name;
int a;
printf("no. of names:");
scanf("%d",&a);
int i;
if( a<=0 )
return 0;
name = (char**)malloc( sizeof(char*)*a);
for(i=0;i<a;i++)
{
printf("enter the name:");
name[i]=(char*)malloc( sizeof(char)*128);
scanf("%s",name[i]);
}
for(i=0;i<a;i++)
{
printf("entered names are:%s\n",name[i]);
free(name[i]);
}
free(name);
return(0);
}
Note I had to cast malloc because the compiler that the OP is using raise the error " cannot convert from 'void ' to 'char ** ' " (which means that it's old enough..)
In
name=(char *)malloc(sizeof(name));
name is a char*, so sizeof(name) is the size of an address. Hence you are not allocating enough memory.
Just allocate more memory:
name=(char *)malloc(sizeof(char)*20); //allocating 20 bytes for the block that name will point tor
In addition to wrong space allocation (answered by brokenfoot), you will not get the results you want because you are reading all the names over and over in the same variable name, and later printing the name input last a times:
for(i=0;i<a;i++)
{
printf("enter the names:");
scanf("%s",name);
}
for(i=0;i<a;i++)
{
printf("entered names are:%s\n",name);
}
The right approach would be to use an array to store all the names, and later print them one by one. For example:
for(i=0;i<a;i++)
{
printf("Enter the names:")
scanf("%s",name[a]);
}
print("The entered names are: ");
for(i=0;i<a;i++)
{
printf("%s", name[a]);
}

Append char to string - the NXC language

I want to write myself a function similar to PHP's str_repeat. I want this function to add specified amount of characters at the end of string.
This is a code that does not work (string argument 2 expected!)
void chrrepeat(const char &ch, string &target, const int &count) {
for(int i=0; i<count; i++)
strcat(target, ch);
}
I don't exactly know what language is that (C++?), but you seem to be passing a char to strcat() instead of a null-terminated string. It's a subtle difference, but strcat will happily access further invalid memory positions until a null byte is found.
Instead of using strcat, which is inefficient because it must always search up to the end of the string, you can make a custom function just for this.
Here's my implementation in C:
void chrrepeat(const char ch, char *target, int repeat) {
if (repeat == 0) {
*target = '\0';
return;
}
for (; *target; target++);
while (repeat--)
*target++ = ch;
*target = '\0';
}
I made it return an empty string for the case that repeat == 0 because that's how it works in PHP, according to the online manual.
This code assumes that the target string holds enough space for the repetition to take place. The function's signature should be pretty self explanatory, but here's some sample code that uses it:
int main(void) {
char test[32] = "Hello, world";
chrrepeat('!', test, 7);
printf("%s\n", test);
return 0;
}
This prints:
Hello, world!!!!!!!
Convert char to string.
void chrrepeat(char ch, string &target, const int count) {
string help = "x"; // x will be replaced
help[0] = ch;
for(int i=0; i<count; i++)
strcat(target, help);
}

LLVM IR String Initialization

I'm working on a program in LLVM IR, and I am trying to initialize a string that says "Hello World!" but I can't figure out how. The goal of the code is to count the number of characters in the string. Before the string needs to be initialized, and after the headers, I have the following:
int main (int argc, const char *argv[]) {
//Setting up
//Build a pointer to the string - LLVMValueRef *strptr=LLVMBuildGlobalStringPtr(builder, const char *string, const char *name);
LLVMValueRef *strptr;
LLVMContextRef context = LLVMContextCreate();
LLVMBuilderRef builder = LLVMCreateBuilderInContext (context);
LLVMModuleRef module1 = LLVMModuleCreateWithNameInContext("mod", context);
}
The easiest way to see how such things are by using the C++ backend - it generates the C++ API calls that build the module for you. You can see this done online.
"Compile" this code:
const char* foo() {
const char* s = "hello world";
return s;
}
And here are the relevant C++ API calls:
GlobalVariable* gvar_array__str = new GlobalVariable(/*Module=*/*mod,
/*Type=*/ArrayTy_0,
/*isConstant=*/true,
/*Linkage=*/GlobalValue::PrivateLinkage,
/*Initializer=*/0, // has initializer, specified below
/*Name=*/".str");
gvar_array__str->setAlignment(1);
// Constant Definitions
Constant *const_array_4 = ConstantDataArray::getString(mod->getContext(), "hello world", true);
std::vector<Constant*> const_ptr_5_indices;
ConstantInt* const_int64_6 = ConstantInt::get(mod->getContext(), APInt(64, StringRef("0"), 10));
const_ptr_5_indices.push_back(const_int64_6);
const_ptr_5_indices.push_back(const_int64_6);
Constant* const_ptr_5 = ConstantExpr::getGetElementPtr(gvar_array__str, const_ptr_5_indices);
// Global Variable Definitions
gvar_array__str->setInitializer(const_array_4);
// Function Definitions
// Function: foo (func_foo)
{
BasicBlock* label_entry = BasicBlock::Create(mod->getContext(), "entry",func_foo,0);
// Block entry (label_entry)
ReturnInst::Create(mod->getContext(), const_ptr_5, label_entry);
}

My strcat doesn't return a value?

I coded a strcat function. But my function doesn't run in this way -----> char * mystrcat(char *s,char *t). I want to return a pointer. Can you help me?
#include <stdio.h>
void mystrcat(char *s,char *t)
{
while(*s!='\0')
s++;
s--;
while((*(s+1)=*t)!='\0')
{ s++;
t++;
}
}
int main()
{
char str[30], str1[30];
gets(str);
gets(str1);
mystrcat(str, str1);
printf("%s\n",str);
return 0;
}
Your function has no return value. If you want to return a pointer from it then just return it. And also void is incorrect for that
When you write void mystrcat(char *s,char *t) you are saying "I will not have a return value" by using void. If you want to return a pointer, this must not be void.
To return a pointer to your string, use char**.
Your string, a series of characters, is represented as a char*.
Here's an example using your code.
#include <stdio.h>
char** mystrcat(char *s,char *t)
{
char *sOrig = s;
while(*s!='\0'){
s++;
}
s--;
while( ( *(s+1) = *t) != '\0')
{
s++;
t++;
}
return &sOrig;
}
int main()
{
char str[30], str1[30];
gets(str);
gets(str1);
char** concatValuePointer = mystrcat(str, str1);
printf("Pointer is %p\n",concatValuePointer);
return 0;
}

Resources