Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add text to a variable in C?

Tags:

c

I'm learning C at the moment and I run into some problem, hard to understand what is going on with variables and adding text to variable in C.

I know C is not treating the strings and character as in other programming language. If I understand it correctly from my book: I have to define a variable before I can use it, that's ok for me. So, If I do this code, where I wish to print the variable text_1 it is failing:

#include <stdio.h>

int main()
{
    char text_1[];
    text_1[] = "Testing";
    printf("Test 1 is: %s", text_1);
return(0);
}

But if I do this way, this is working:

#include <stdio.h>

int main()
{
    char text_1[] = "Testing";
    printf("Test 1 is: %s", text_1);
return(0);
}

In some other programming language I can do this way: Dim a as string

a="Testing"
print("Testing 1 is:", a) --> or similar option to print out the variable 'a'.

What is the correct way to do this in C?

Thank you.

like image 210
Chris Avatar asked Nov 17 '25 09:11

Chris


1 Answers

Oops... C language is a rather low level language if you compare it to Java, Python or Ruby, or even Basic or JavaScript:

  • it has no notion of text string but only uses null terminated character arrays in its standard library
  • arrays by themselves are not first class citizens: except at initialization time, the language can only process arrays elements and not the full array

Long story made short, an array has a size that is defined only once (at definition time) and will never change during the life time of the array. char text_1[] = "Testing"; is an idiomatic initialization: the size of the array is set to the number of characters of the literal string + 1 for the terminating null, so here 8. After that text_1 will be able to contain other strings of at most 7 characters + 1 terminating null if you copy the relevant character for example with strcpy.

To go back to your code, char text_1[]; declares an incomplete array with a declared size of 0 bytes. That means that you cannot use it. The 2 correct ways would be:

char text_1[] = "Testing";   // idiomatic initialization of a 8 characters array

or

char text_1[8];              // definition of an uninitialized char array of size 8
strcpy(text_1, "Testing");   // copy a string into the array

Not really sexy, but C language is like that...

like image 193
Serge Ballesta Avatar answered Nov 18 '25 23:11

Serge Ballesta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!