w3resource

C programming: What is the difference between char a[] and char *a?

Difference between char a[] and char *a.

It is important to understand that 'char a[]' and 'char *a' are different ways of representing strings in C language.

char a[] is an array of characters. It is a fixed-size block of memory allocated on the stack, and its size cannot be changed at runtime. It is possible to modify the contents of the array, but the pointer to the first element a cannot be reassigned to point to another memory address.

Code:

# include <stdio.h>

int main() 
{
 char a[] = "python";
 a[0] = 'P';
 printf("%s\n", a); 
 return 0;
}

Output:

Python

char *a is a pointer to a character. It is a variable that holds the memory address of the first element of a character array or a string. The size of the array is not fixed, and it can be dynamically allocated using memory allocation functions like malloc(). It is possible to modify the contents of the array through the pointer, and to reassign the pointer to another memory address.

Code:

#include <stdio.h>
int main() 
{
char *a = "hello";
// Following line create a runtime error because string literals are read-only
//a[0] = 'H';
a = "world";
printf("%s\n", a); 
return 0;
}

Output:

world

Contribute your code and comments through Disqus.



Follow us on Facebook and Twitter for latest update.

C Programming: Tips of the Day

C Programming - How do you pass a function as a parameter in C?

Declaration

A prototype for a function which takes a function parameter looks like the following:

void func ( void (*f)(int) );

This states that the parameter f will be a pointer to a function which has a void return type and which takes a single int parameter. The following function (print) is an example of a function which could be passed to func as a parameter because it is the proper type:

void print ( int x ) {
  printf("%d\n", x);
}

Function Call

When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this:

func(print);

would call func, passing the print function to it.

Function Body

As with any parameter, func can now use the parameter's name in the function body to access the value of the parameter. Let's say that func will apply the function it is passed to the numbers 0-4. Consider, first, what the loop would look like to call print directly:

for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
  print(ctr);
}

Since func's parameter declaration says that f is the name for a pointer to the desired function, we recall first that if f is a pointer then *f is the thing that f points to (i.e. the function print in this case). As a result, just replace every occurrence of print in the loop above with *f:

void func ( void (*f)(int) ) {
  for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
    (*f)(ctr);
  }
}

Ref : https://bit.ly/3skw9Um