Jump to content

Search the Community

Showing results for tags 'c'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

There are no results to display.

There are no results to display.


Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


Website URL


LinkedIn Profile URL


About Me


Cloud Platforms


Cloud Experience


Development Experience


Current Role


Skills


Certifications


Favourite Tools


Interests

Found 7 results

  1. One of the useful statements that we can use in the C programs is the goto statement. Even though its sometimes discouraged for making code unreadable, it’s a fundamental feature of the C Language that is sometimes needed. This statement allows us to control the flow of a program by jumping to and from various parts of the program. In this tutorial, we will learn what this statement does, how it works, and the various instances it can come in handy. NOTE: It is good to keep in mind that the goto statement is not widely used. It tends to create some unnecessarily complex code but it can be effective, and learning about it can help you avoid its pitfalls. goto Statements Goto, as the name suggests, allows us to transfer the control of a program from one part to another without using any conditional statement evaluation. It provides a form of low-level and manual control flow. Unlike the conditional statements that evaluate a condition and then perform an action, the goto statement just switches to another part of the code without any context. As a result, it often leads to spaghetti code which is basically a code that is hard to understand due to lack of defined structure or foundation on the resulting actions. Think of a bowl and twisted spaghetti, using the goto statements incorrectly can lead to such a code that makes you want to off yourself due to lack of coherent structure in the execution. What does goto do? In simple terms, when the program encounters a goto statement, the program jumps to the specified label which automatically bypasses any code that is defined between the goto statement and the target label. You can use it to, for example, break out of a loop, handle the errors, or simply with complex cases of nested statements. goto syntax The following shows the basic syntax of the goto statement in C: goto label; //... label: // logic at the label We start with the “goto” keyword followed by the name of the label that we wish. We then call the actual label and specify the code that we wish to run. Example: Break Out of a Loop with goto Let us look at a basic example that demonstrates the use of the goto statement to break out of a loop: #include <stdio.h> int main() { int i = 0; start: printf("Value of i: %d\n", i); i++; if (i < 5) goto start; return 0; } In this example, we start by declaring a positive integer variable and initialize its value to 0. We then create a label called “start”. In C, the labels are followed by a colon to denote that they are targets for the goto statement. In the label, we print the value of “i” to the console and increment the value of “i” by 1 on each iteration. Next, we setup a goto statement that unconditionally jumps to the “start” label. This creates a loop that jumps back to the start label as long as the value of “i” is less than 5. Run the previous code as follows: Value of i: 0 Value of i: 1 Value of i: 2 Value of i: 3 Value of i: 4 It is good to keep in mind that if you want to deal with loops in a more effective and efficient manner, use other constructs such as the “for” and “while” loops. Unless you closely examine the given code, you can hardly tell that there is a loop in the code. Conclusion In this tutorial, we explored the fundamentals and workings of the goto statements in C/C++, how it works, and how to use it. We strongly recommend to avoid using the goto statements unless you explicitly need to. View the full article
  2. The C language has several functions that allow to read the files, the most commonly used are the read() and fread() functions. This language also provides methods to read the character by character with functions such as getchar(). It is important to know the file processing functions, their call methods, input and output arguments, etc. in order to use them fluently because they are the available resource to the programmer to store and dispose off the information that is stored in the system. In this Linuxhint article, you will learn how to use the read() function to read the files. We’ll explain everything about this ella, its syntax, the method call, the input and output arguments, the type of data they each accept, and how to declare them properly. We then apply what we learned by putting the use of this feature into practical examples. In order for you to be fully aware on how to use the read() function, we added a special section that describes all the errors that can occur when using this function, as well as their detection and identification, so that you will have the necessary techniques for a quick solution in case of an error. Syntax of the Read() Function in C Language size_t read(int fd, void *buf, size_t count); Description of the Read() Function The read() function reads the contents of the open file that is specified by its descriptor in the “fd” input argument. This function reads and copies the contents of the file into the buffer that is pointed to by “buf” with the count number of bytes. The “fd” identifier is an integer that is returned as the result of the open() function when the file is opened. If the read() function returns successfully, it returns the number of bytes read. A result equal to 0 means that the file was read to the end, and -1 means that an error occurred. The specific error can be identified by retrieving its code from the global “errno” variable. Later, you will find a section that describes the errors that can occur when using the read() function and the techniques to detect and identify them. The read() function is declared in the “unistd.h” header. To use it, you must include this file in your code as follows: #include <unistd.h> How to Read a File with the Read() Function In this example, we will explain how to open and read a file using the open() and read() functions. For this purpose, we previously created a text file with the “example.txt” name via the Linux Manager and saved it in the “Documents” directory. Then, we wrote the first paragraph of this article in it. The first step in developing the code to read the file is to include the necessary headers and create a main() function that returns an empty value. We define the “fd” integer in it which serves as the file descriptor, a 1024 character buffer called “buff” where the information that is read by read() is stored. The array path stores the path and the name of the file that we want to read. After defining the necessary variables, we call the open() function to open the file. We call this function by passing the path array with the path and name of the file as the first input argument and specifying the O_RDONLY flag as the second argument. As the output argument, we pass the “fd” integer where open() returns the descriptor that we then use to read to the file. Once we have the file open, we read its contents by calling the read() function and passing the “fd” descriptor as the first argument that is returned by the open() function. As the second argument, we pass the pointer to the “buff” buffer where we store the contents to be read and finally the size of the buffer which, in this case, is 1024 bytes. We then use the printf() function to display the contents that are stored in buff in the command console. Here is the complete code for this example: #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> int main() { int fd; char buff[1024]; char path[] = "Documents/example.txt"; fd = open(path, O_RDONLY); read(fd, buff, 1024); printf("\n\n%s\n\n",buff); } In the following figure, we see the compilation and execution of this code. As we can see, read() puts the entire contents of the “example.txt” file into “buff” and the printf() function prints it to the command console: How to Detect and Identify the Errors that Can Occur When Using the Read() Function Using read() can generate various errors. When this happens, this function returns a result that is equal to -1. The easiest way to determine if an error has occurred is to use an “if” condition where the condition is the return value of -1. Now, let us see how you can use this method to determine if an error has occurred: int n; n = read(fd, buff , 1024); if ( n == -1){ printf ("An error occurred while trying to read the file."); } If the read() function returns with an error, it transitions to the “if” statement and prints the “An error occurred while trying to read the file” message. When an error occurs, a numeric code is automatically stored in the global “errno” variable which is defined in the “errno.h” header. This code can be used to identify the error that occurred. The following is an excerpt with the errors that the read() function can generate and that are defined in the “errno.h” header, along with a brief description of each error and the associated integer value: Definition Value in errno Error EAGAIN 11 Try again EBADF 9 Incorrect file number EDESTADDRREQ 89 Destination address required EFAULT 14 Incorrect address EFBIG 27 File too big EINTR 4 System call interrupted EINVAL 22 Invalid argument EIO 5 I/O error EPERM 1 Operation not allowed The easiest way to identify an error is to open a switch where the “errno” variable is the jump condition and each case is an error definition. Next, let us look at an example where we try to enter a descriptor with a negative sign, resulting in an error. To identify an error, we use the “if” condition that we saw in the previous snippet. To identify it, we open a switch with the three most common errors that this function can produce. #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> int main() { int fd,n; char buff[1024]; char path[] = "Documents/example.txt"; fd = open(path, O_RDONLY); n = read(99999999, buff, 1024); if (n == -1){ switch(errno){ case EBADF:{ printf("Bad file number. Error: %i\n", errno); break;} case EINVAL:{ printf("Invalid argument. Error: %i\n", errno); break;} case EIO:{ printf("I/O error . Error: %i\n", errno); break;} } } } As we can see in the following figure, the read() function returns an error when an invalid descriptor is passed as an input argument, and the value that is retrieved from the “errno” variable that is used as a jump condition allows us to identify the error when entering the EBADF case. Conclusion In this Linuxhint article, we showed you how to use the read() function, one of the most common functions that is implemented in the C language to read the files. We looked at its syntax and a section that describes its theoretical operation, input and output arguments, and its data types. Afterwards, we implemented what we learned in a practical example with the code and images that show how to open and read a file using the open() and read() functions. To have the necessary means to troubleshoot a possible error when using this function, we added a special section that explains the methods that the C language provides to detect and identify the errors. View the full article
  3. When we develop the programs that require a user interaction, there are cases where it is necessary to adjust the system times so that the application is readable and easy to use. For example, if we are developing a console application where we need to inform the user of the tasks that are executed in sequence, the information messages should persist for a reasonable time so that the user has time to read them before they are cleared and the program moves on to the next command. In this Linuxhint article, you’ll learn how to use the sleep() function to create delays in real time. We’ll show you the syntax and description of this function, as well as the options that POSIX provides to create delays with fractions of less than a second. Then, using practical examples, code, and pictures, we’ll show you how to delay the execution of a program and the effects of signals on this function. Syntax of the Sleep() Function: unsigned int sleep ( unsigned int sec ) Description of the Sleep() Function in C Language The sleep() function puts the process or thread to sleep for the time in seconds that is specified in the “sec” input argument which is an unsigned integer. Once the sleep() function is called, the calling process sleeps until it times out or receives a signal. This function is often used to enforce long delays of more than 1 second in the execution of real-time processes. For the delays of less than 1 second, POSIX provides the microsecond resolution the usleep() function which uses the same method call as sleep(). For the delays of less than 1 microsecond, there is also the nanosleep() function with a resolution of 1 nanosecond, but with a different call method where it uses the timespec structures as input arguments to set the delay time. If the sleep() function has consumed all of the specified time, it returns 0 as the result. If the execution is interrupted by the arrival of a signal before the specified time has elapsed, it returns the remaining number of seconds until that time. The sleep() function is defined in the “unistd.h” header. To use it, we need to include this file in the code as follows: #include <unistd.h> How to Introduce Delays in a Process with the Sleep() Function in C Language In this example, we create a timer that consists of an infinite loop in which we print the “Elapsed time” message in the command console, followed by the elapsed seconds of the process. Each of these loops is repeated every 2 seconds due to the delay that is caused by the sleep() function. To do this, we take an empty file with the “.c” extension and add the “stdio.h” and “unistd.h” headers in it. Then, we open an empty main() function and define in it the “seconds” variable of type int which we use as a counter for the elapsed time. Once the headers are inserted and the variable is declared, we open an infinite loop and use the printf() function in it to display the message and the time value. On the next line, we increment the time variable by 2 and then call the sleep() function with the value of 2 as the input argument. In this way, this cycle is repeated every second and we get a counter that displays the elapsed time on the screen. Now, let’s take a look at the code for this application. In the following, we can see the complete code for this example: #include <stdio.h> #include <unistd.h> void main () { int seconds =0; while (1) { printf("Elapsed time: %i\n", seconds); seconds +=2; sleep(2); } } We can see the following image with the compilation and execution of this code. As we can see, every 2 seconds, the program prints on the screen the seconds elapsed since the execution of the process: Effect of Signals on the Sleep() Function In this example, we want to observe the effect of signals on a process that is put to sleep using the sleep() function. To do this, we create a simple application consisting of a main() function and a handler for signal 36. In the first line of the main() function, we declare the remaining variable of type int where we store the value that is returned by the sleep() function. Then, we use the signal() function to bind the handler to signal 36. On the next line, we display the PID of the process which we then use to send a signal from a second shell to the process. Finally, we call the sleep() function and set its input argument to 60 seconds which is long enough to send a signal from a second shell. As the output argument to sleep(), we send the remaining variable. The handler that is attached to signal 36 consists of a line of code where the printf() function prints the “Time remaining:” message followed by the value that is returned by sleep() at the time the signal arrives at the process. Next, we see the code for this example: #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <signal.h> void handler ( int remaining); void main () { int remaining; signal (36, handler); printf("Process ID: %i\n", getpid()); remaining = sleep(60); } void handler (int remaining) { printf("Time remaining: %i\n", remaining); } The image that we see in the following shows the compilation and execution of this code: To see the effect of the signals in this process, we compile this code and run it. Then, from a second terminal, we send a signal with the following syntax: kill -n signal PID The image that we see in the following shows in the console above the execution of this code and the effects of the arrival of a signal that is sent from the console below. As you can see, the signal has suppressed the effect of the sleep() function by waking up the process. Conclusion In this Linuxhint article, we showed you how to use the sleep() function to put a process to sleep for a specified number of seconds. We also showed you the syntax as well as the description of the function and the calling method. Using practical examples, code snippets, and pictures, we showed you how to put a process to sleep and what affects the arrival of a signal has on a sleeping process using the sleep() function. View the full article
  4. Operators are the main foundation of any programming language as they help users perform mathematical and numerical operations on operands. With the help of these operators, the users will be able to operate operands. There are different types of built-in operators in C: arithmetic, logical, relational, bitwise, equality, and others. This article will discuss relational and equality operators in the C programming language. C Relational and Equality Operators Relational and Equality Operators are C operators used to compare two values as they determine the relation between them. These operators include “equal to (=)”, “not equal to (!=)”, also called Equality operators. While they also include relational operators like “less than (<)”, “greater than (>)”, and a combination of both relational and equality operators like “less than or equal to (<=)” and “greater than or equal to (>=)”. Let’s discuss each operator in detail. 1: Equal to Operator (=) The equal to (=) operator is a type of equality operator used in a code to compare the values. It compares two values in a code and returns True if both are equal. 2: Not Equal to Operator (!=) The not equal to (!=) operator in C language compares the two values and returns the result as True if both values are not equal. 3: Less than Operator (<) This operator compares the two values and returns the statement as True if the first value is less than the second value. Otherwise, it considers it False. 4: Greater than Operator (>) This is another relation operator that compares the two values and outputs the result to True if the first value is greater than the second value. 5: Less than or Equal to Operator (>=) This operator checks the two values in a condition, and in the first case, it checks whether the first value is greater than the second value; if it’s not, it checks whether both are equal. If any condition meets, you will see the output as True. Otherwise, it outputs False. 6: Greater than or Equal to Operator (>=) This is another useful operator that checks the comparison of two values. If the two values meet any condition greater or equal to, it generates the result as True, otherwise, it considers the statement as False. Let’s follow up with a simple example below that relates to all these operators discussed above. #include <stdio.h> int main() { int X =6, Y =10; // equal to if (X == Y) printf("X is equal to Y\n"); else printf("X and Y are not equal\n"); // not equal to if (X != Y) printf("X is not equal to Y\n"); else printf("X is equal Y\n"); // less than example if (X < Y) printf("X is less than Y\n"); else printf("X is greater than or equal to Y\n"); // greater than example if (X > Y) printf("X is greater than Y\n"); else printf("X is less than or equal to Y\n"); // lesser than equal to if (X <= Y) printf("X is lesser than or equal to Y\n"); else printf("X is greater than Y\n"); // greater than equal to if (X >= Y) printf("X is greater than or equal to Y\n"); else printf("X is lesser than Y\n"); return 0; } In the above code, two numbers X and X are given. The code checks each condition one by one. Those conditions that are met will print at the output shown below: Output In this way, you can use these relational and equality operators in C. Conclusion Relational and Equality Operators are C operators used to compare two values as they determine the relation between them. These operators include ”equal to (=)”, ”not equal to (!=)”, also called Equality operators. While they also include relational operators like less than (<), more significant than (>) and a combination of both relational and equality operators like less than or equal to (<=) and greater than or equal to (>=). View the full article
  5. In this Linux Hint article, you will learn how to enter the world of programming by creating a program that prints the classic phrase, “Hello world”, on the command console. To have all the means to understand and implement the code snippets that we will show you, we will first explain step-by-step on how to create a file with the “.c” extension to develop a program in the C language. In a special section, we will also show you how to compile the code with GCC and run a program from the Linux command-line. Then, we will show you how to insert the necessary headers, create the main() function, and generate the “Hello world” program. How to Create a File with the “.c” Extension to Write a Program in It Every program in this language starts with a file with the “.c” extension, in which the main function of the process is written, including the necessary headers which define the functions and variables that are used. To create such a file, we need to call the Linux file manager and press the right mouse button in the directory where we want to save it. This displays an options menu where we must left-click on the “Create new document” option and select “Empty document” from the menu that displays. Once we create the file, we select it, press the right mouse button, and select “Properties” from the pop-up menu. Click accept in the file name where we add the “.c” extension under “Properties”. Then, close it. In this way, we create a file that can be compiled by any compiler on any platform. How to Compile and Run the Code Compiling and running a program is a necessary step in understanding the examples that follows. Therefore, in this section, we will show you how to do this task. To compile a file in the C language, we need to open the Linux command console and use the following command syntax: ~$ gcc path/filename.c -o out-name GCC calls the compiler that compiles the specified file in the path/name.c, and -o specifies the name of the executable that results from the compilation. If the code contains errors, the compiler returns a message for each reported error. If it succeeds, it returns nothing. To run the output, we must use the following command syntax: ~$ ./out-name The name of the output must always be preceded by the “./” characters. How to Include the Headers in the “.c” File After opening the file, include the header that defines the functions that we use. The headers in the C language have the “.h” extension and are inserted into the program with the following syntax: #include <header name.h> In this case we only use the “stdio.h” header. In this header, the standard input and output functions are defined as the printf() function which we will use later. The headers are the first thing that the compiler must read. Therefore, they must appear in the code in the first place before the definitions and the main() function. How to Create the Main() Function to Write the Program Inside It Every C language program starts with the main() function. From there, the variables are defined, the data is processed, and the functions are called. The main() functions can either go out and return empty, go out empty and return with data, or vice versa. In this case, it goes out empty and returns the same way. Now, let us look at the syntax to create a main() function of this type: Void main () { } The compiler processes everything between the two curly braces as part of the main() function. How to Call the Printf() Function to Write in the Command Console In this step, we call the printf() function to write the “Hello world” string to the command console. When you call a function in the C language, its input arguments must always be enclosed in parentheses and separated by commas if there is more than one. All function calls, declarations, statements, etc. must end with the “;” character. The simplest method of calling the printf() function is to send a simple string as the only input argument. A string in the C language is a fragment of text between quotes that are stored in a data array of type char. These fragments are composed of alphanumeric characters, symbols, and control characters. In the following, we see the complete program with the call method of the printf() function which writes the “Hello world” sentence to the command console: #include <stdio.h> void main () { printf("Hello World"); } The following figure shows the compilation and execution of this code. As you can see, the “Hello World” phrase is printed on the same line as the prompt: Escape characters have a control function in strings. For example, the “\n” character before the string writes it to a new line. This character after the string writes it and moves the cursor to the next line. Let us see what happens when we insert these escape characters before and after the string, as the following code shows: #include <stdio.h> void main () { printf("\nHello World\n"); } As can be seen in the following figure, the string is written to a new line in this case. Then, the cursor is moved next. This causes the command console prompt to be written in a new line in the following example: Conclusion In this Linux Hint article, we take the first step into the world of programming by explaining from scratch how to create a file with a “.c” extension to write a program in. We also included a section where we show you how to compile with GCC and run the written program from the Linux command console. Then, we showed you how to include the headers, create a main() function, and briefly explain what a string is in the C language. We also showed how to use the printf() function and its method call to write the “Hello World” classic phrase to the Linux command console. View the full article
  6. Conditional loops are a great resource in programming. They can be found in many functions in the various C language libraries and have the task of repeating a code snippet until it is released from the loop by an escape condition. In this Linux Hint article, you will learn how to use the do-while conditional loop, a variant of the “while” loop with a different escape method that is very useful in certain cases. We will see the various options that the C language offers for conditional loops and a brief description of each one. Then, we’ll take a detailed look at how the do-while loop works, and explain its escape method and the relational operations that control it. We will also apply what we learned through the practical examples with code snippets and images that show the use of this conditional loop in different cases. Conditional Loops in C Language A conditional loop repeats the execution of the code that it encloses in curly braces until the escape condition is met, which releases the program from the loop. The escape condition is determined by a relational operation where a “false” result exits the program loop while a “true” result keeps it inside. The expression for this operation must be enclosed in parentheses and must preceded by the name of the loop as shown in the following: while ( relational operation ) Next, let us look at a brief description of the two conditional loop options which are provided by the C language. Each of them has functionality that adapts to the particular requirements of the case. Then, we will look at the do-while statement, a variant of the while loop, in detail. While Loop The conditional “while” loop repeats its cycle as long as the value of a variable does not satisfy the escape condition. Let us look at an example where the escape condition in this case is “a” equals “0”: while ( a!=0 ){ //code… } For Loop The “for” loop provides a way to declare a variable and apply a relational operation to the result of an arithmetic or logical operation on that variable. If the result of the relation is false, the program exits the loop and continues its execution. If the result does not match, the loop repeats in the same way as the “while” loop. Let us look at the syntax of this conditional loop: for (Variable declaration, relational operation, arithmetic operation) In the following illustration, we see a code fragment in which the variable a is declared with the value 0, the arithmetic operation “a+2” is applied to it, and the relational operation “a!=100” is applied to the result: for ( int a =0; a!=100; a+2){ //code } In this case, the program runs through 50 cycles of the “for” loop before breaking out of it. Do-While Loop Syntax in C Language do{ code… }while (condition); Description and Examples of the Conditional Do-While Statement in the C Language The conditional do-while statement works the same as the while statement, but in reverse order. That is, “while” analyzes the escape condition at the beginning of the loop, and “do-while” does so at the end. This guarantees that the program runs through the code by enclosing the loop at least once, regardless of whether the escape condition is met or not. The difference between the “while” and “do-while” statements is the point in the loop where the output is determined. Let us look at what happens in a “while” loop when the escape condition is specified before entering it: #include <stdio.h> void main() { printf ( "\nStart program...\n"); while (0 != 0){ printf ( "\nInside loop\n"); } printf ( "\nEnd program\n"); } In the following figure, we see the result of compiling and executing this code. Since the escape condition was given before the “while” loop was reached, the program jumps to the end of the loop without executing the code inside. Let us see what happens if we replace the “while” statement with a “do-while” statement with the same condition: #include <stdio.h> void main() { printf ( "\nStart program...\n"); do{ printf ( "\nInside loop\n"); }while (0 != 0); printf ( "\nEnd program\n"); } In the following figure, we see the result of compiling and executing this code. As you can see, although the escape condition is specified before entering the loop, as in the previous example, the program in this case enters it and executes the code one pass. Nested Do-While Loops in the C Language Just like other conditional loops, the C language allows the nesting of “do-while” loops. We see an example where one of these loops is nested inside another as shown in the following: #include <stdio.h> void main() { int a =3; int b=3; printf ( "\nStart program..."); do{ printf ( "\nloop 1"); a--; do{ printf ( "\n loop 2"); b--; }while (b != 0); b=3; }while (a != 0); printf ( "\nEnd program\n"); } The image that we see in the following illustration shows the compilation and execution of this code where two nested “do-while” loops are executed. Conclusion In this Linux Hint article, we showed you how to use the conditional “do-while” loop. We started with an introduction which explains what the conditional loops are consist of and discussed the different options available in the C language, briefly describing each of them, their development, and their use. We also discussed the details with the theoretical explanation of the “do-while” loop by showing you how it works, the relational operations that determine the escape condition, and the differences between this variant and the “while” loop. We then put what we learned into practice with code snippets and images that show how to develop a program with the simple or the nested “do-while” loops. View the full article
  7. A string in C language is an array of characters that is terminated with a null character (\0). The string length is the number of characters in a string. In the string length ‘\0,’ a character is not counted. In the example shown above, the length of the string str is 6. In this tutorial, first, we will show how to use a user defined function to calculate length of a string, and then we will show you a built-in library function strlen(). We also show you the uses of the sizeof operator for string literals. String Length Using User Defined Function You can write a user defined function which returns the number of characters in a string. //Example1.c #include<stdio.h> int stringLength(char *str) { int i=0; while(str[i] != '\0') i++; return i; } int main() { char str[30]= "STRING"; printf("Length of the string str is => %d\n",stringLength(str)); return 0; } Here, we iterate the while loop from i = 0 until we do not encounter the ‘\0’ character. The value of i is increased by 1 in each iteration of the while loop. When the loop ends, the value of i is the length of the string. String Length Using Built-In Library Function The built-in library function strlen() can also be used to determine string length. strlen() function: Header file: string.h Syntax: size_t strlen (const char *str) Argument: This function takes an argument of the type pointer to char. Return value: This function returns the length of the string str. Note that size_t is just an alias of an unsigned integer. //Example2.c #include<stdio.h> #include<string.h> int main() { char str1[30]="STRING ARRAY"; char *str2; char *str3; str2 = str1; str3 = "STRING POINTER"; printf("Length of the string str1 is => %ld\n",strlen(str1)); printf("Length of the string str2 is => %ld\n",strlen(str2)); printf("Length of the string str3 is => %ld\n",strlen(str3)); printf("Length of the string "STRING LITERALS" is => %ld\n",strlen("STRING LITERALS")); return 0; } Here, we pass string array, string pointer, and string literal to the strlen function, and the function returns the length of the string. String Length Using sizeof Operator We also can use the sizeof operator for string length (only for string literal). But, we have to subtract 1 from the value returned by this operator, because it also counts the’\0’ character. For array and pointer, the sizeof operator returns the allocated size of the array and the pointer, respectively. //Example3.c #include<stdio.h> int main() { char str1[30] = "STRING"; char *str2 =str1; printf("Length of "STRING" is => %d\n",(sizeof("STRING") - 1)); printf("Allocated size of the str1 array is => %d\n",sizeof(str1)); printf("Size of the str2 pointer is => %d\n",sizeof(str2)); return 0; } Here, in Line no 9, we pass the string literal “STRING” and get the size, including the ‘\0’ character. So, we subtract 1 and get the actual size of the string. When we pass an array to the sizeof operator, it returns the allocated size of the array, which is 30, and when passing a character pointer, it returns the size of the pointer. Conclusion So, in this tutorial, we have shown you how string length can be calculated in various ways. You can use in your code whichever method is best suited for you. View the full article
  • Forum Statistics

    63.6k
    Total Topics
    61.7k
    Total Posts
×
×
  • Create New...