pradeep
pradeep

Reputation: 9

convert arrayof characters to string

I am writing code in c language.

  1. char a[]={p,r,a,d,e,e,p}
    I want to add '0/' at the end to make it string.
    Or is there any method to make it string other than adding null at the end?

  2. char *a=pradeep;
    Convert this to string by adding null at the end

Upvotes: 1

Views: 203

Answers (5)

Denys Séguret
Denys Séguret

Reputation: 382132

char *a="pradeep";

makes a string literal and adds the null character at the end.

If you really want to declare it using a syntax similar to your 1, you may do this :

char a[] = {'p','r','a','d','e','e','p', 0};

but there is no reason to do this.

EDIT Regarding the question in comment

If you want to create a string from n characters you receive, you may do this :

char *a = malloc(n*sizeof(char)+1);

If it's always 10 chars or less, you may declare it as

char a[11];

Then set each a[i] with the received value, and the last one with 0.

You could also use sprintf to do the concatenation but in any case you must ensure you have enough place allocated.

Upvotes: 1

hmjd
hmjd

Reputation: 121971

You can't change the size of the array a so you cannot add a null terminator to it. You could change the declaration to:

char a[] = "pradeep";

which will implicitly add the null terminator. Or:

char a[] = { 'p', 'r', 'a', 'd', 'e', 'e', 'p', 0 };

but the string literal is simpler and clearer. Most, if not all, of the C string library functions require a null terminated string.

Upvotes: 3

Some programmer dude
Some programmer dude

Reputation: 409166

If you assign a literal string to a character array, the compiler will automatically create the correct array with the terminating '\0' character at the end:

char a[] = "pradeep";

The above is the same as writing

char a[] = { 'p', 'r', 'a', 'd', 'e', 'e', 'p', '\0' };

Also, using arrays is the recommended way, but the first alternative above is equivalent to

char *pa = "pradeep";

However, with this last, you can no longer use the sizeof operator, as that will return the size of the pointer and not the length of the string. Another note about the sizeof operator, for the first two examples, it will return the size of the array and not the length of the string, i.e. sizeof for a character array will include the terminating character.

Upvotes: 0

perilbrain
perilbrain

Reputation: 8197

1). char a[]={'p','r','a','d','e','e','p','\0'};

Now its an array containing a valid string.

2). char *a="pradeep"; 

This automatically appends null at end to make valid string.

Upvotes: 1

unwind
unwind

Reputation: 399803

Your code doesn't make any sense, and won't compile.

String literals are best written using string literal syntax:

const char *a = "pradeep";

This will include the terminating character, making a point at a C string that you can use with any of the string-processing functions, print out, and so on.

Upvotes: 1

Related Questions