I have recently started to code in C and I am having quite a lot of fun with it.
But I ran into a little problem that I have tried all the solutions I could think of but to no success. How can I assign a char* variable to an array?
Example
int main()
{
char* sentence = "Hello World";
//sentence gets altered...
char words[] = sentence;
//code logic here...
return 0;
}
This of course gives me an error. Answer greatly appreciated.
You need to give the array words a length
char words[100]; // For example
The use strncpy to copy the contents
strncpy(words, sentence, 100);
Just in case add a null character if the string sentence is too long
words[99] = 0;
Turn all the compiler warnings on and trust what it says. Your array initializer must be a string literal or an initializer list. As such it needs an explicit size or an initializer. Even if you had explicitly initialized it still wouldn't have been assignable in the way you wrote.
words = sentence;
Please consult this SO post with quotation from the C standard.
As of:
How To Assign char* to an Array variable ?
You can do it by populating your "array variable" with the content of string literal pointed to by char *, but you have to give it an explicit length before you can do it by copying. Don't forget to #include <string.h>
char* sentence = "Hello World";
char words[32]; //explicit length
strcpy (words, sentence);
printf ("%s\n", words);
Or in this way:
char* sentence = "Hello World";
char words[32];
size_t len = strlen(sentence) + 1;
strncpy (words, sentence, (len < 32 ? len : 31));
if (len >= 32) words[31] = '\0';
printf ("%s\n", words);
BTW, your main() should return an int.
I think you can do it with strcpy :
#include <memory.h>
#include <stdio.h>
int main()
{
char* sentence = "Hello World";
char words[12];
//sentence gets altered...
strcpy(words, sentence);
//code logic here...
printf("%s", words);
return 0;
}
..if I didn't misunderstand. The above code will copy the string into the char array.
How To assign char* to an Array variable?
The code below may be useful for some occasions since it does not require copying a string or knowing its length.
char* sentence0 = "Hello World";
char* sentence1 = "Hello Tom!";
char *words[10]; // char *words[10] array can hold char * pointers to 10 strings
words[0] = sentence0;
words[1] = sentence1;
printf("sentence0= %s\n",words[0]);
printf("sentence1= %s\n",words[1]);
Output
sentence0= Hello World
sentence1= Hello Tom!
The statement
char* sentence = "Hello World";
Sets the pointer sentence to point to read-only memory where the character sequence "Hello World\0" is stored.
words is an array and not a pointer, you cannot make an array "point" anywhere since it is a
fixed address in memory, you can only copy things to and from it.
char words[] = sentence; // error
instead declare an array with a size then copy the contents of what sentence points to
char* sentence = "Hello World";
char words[32];
strcpy_s(words, sizeof(word), sentence); // C11 or use strcpy/strncpy instead
The string is now duplicated, sentence is still pointing to the original "Hello World\0" and the words
array contains a copy of that string. The array's content can be modified.
Among other answers I'll try to explain logic behind arrays without defined size. They were introduced just for convenience (if compiler can calculate number of elements - it can do it for you). Creating array without size is impossible.
In your example you try to use pointer (char *) as array initialiser. It is not possible because compiler doesn't know number of elements stayed behind your pointer and can really initialise the array.
Standard statement behind the logic is:
6.7.8 Initialization
...
22 If an array of unknown size is initialized, its size is determined
by the largest indexed element with an explicit initializer. At the
end of its initializer list, the array no longer has incomplete type.
I guess you want to do the following:
#include <stdio.h>
#include <string.h>
int main()
{
char* sentence = "Hello World";
//sentence gets altered...
char *words = sentence;
printf("%s",words);
//code logic here...
return 0;
}
Related
I have the following simple program which creates a pointer to the first character of a string:
char str[] = "Hello world";
char *p = &str[0];
How can I then get this string back into a variable using only the pointer?
Dereferencing the pointer just gives the first character of the string - as somewhat expected - so I'm assuming that there is no 'simple' way to achieve this and it will instead require writing extra code.
The current way I would approach this would be as follows:
Iterate from the pointer until a null terminator is reached to find the length of the string
Create a new char array with this length
Iterate through again inserting characters into this array
Is there a library function to achieve this, or if not, a simpler way that doesn't involve iterating twice?
Yes you have to "do it by hand". Because there are no objects in C - you need to take care of all that happens in the code.
You can use malloc, strlen and memcpy:
char str[] = "Hello world";
char *p = malloc(strlen(str) + 1);
if (!p) { abort(); }
memcpy(p, str, strlen(str) + 1);
You can use strcpy and forget about one strlen:
char *p = malloc(strlen(str) + 1);
if (!p) { abort(); }
strcpy(p, str);
Or you can use strdup from POSIX or a C extension:
char *p = strdup(str);
if (!p) { abort(); }
...
Is there a library function to achieve this, or if not, a simpler way that doesn't involve iterating twice?
As said in comment, strdup() will do exactly what you want. But here there is another problem (by your point of view): strcpy() will iterate the string twice, because there is no other way to duplicate a string.
By definition, strings in C are a sequence of characters somewhere in memory, with the last one character being a NUL (with single L), the value 0 (in a char). References to strings are pointers to the first character in the sequence depicted above. Note that two different strings can point to the same memory (they are not so different then...), or a string can point into the middle of another. These two cases are somewhat particular but not uncommon. The memory for strings must be managed by the programmer, who is the only one to know where allocate and deallocate space for strings; functions like strcpy() do nothing special in this regard, they are (presumably) well written and optimized, so maybe to copy a string the behavior is not plain as I depicted it before, but the idea is the same.
try this code:
#include "stdio.h"
int main(){
char str[] = "Hello world";
int count = 12;
char (*p)[12] = &str;
printf("%c\n",(*p)[0]);
printf("%c\n",(*p)[1]);
printf("%c\n",(*p)[2]);
printf("%c\n",(*p)[3]);
printf("%s\n",(*p));
}
Here's how I would make a copy of a string using only the standard library functions:
#include <stdio.h> // printf
#include <stdlib.h> // malloc
#include <string.h> // strcpy
int main(void)
{
char str[] = "Hello world"; // your original string
char *p = (char *)malloc(strlen(str) + 1); // allocate enough space to hold the copy in p
if (!p) { // malloc returns a NULL pointer when it fails
puts("malloc failed.");
exit(-1);
}
strcpy(p, str); // now we can safely use strcpy to put a duplicate of str into p
printf("%s\n", p); // print out this duplicate to verify
return 0;
}
I'm doing simple c excercise using visual studio.
Using strcat_s function I receive a violation exception thru this code:
char *str1;
str1 = (char *)malloc(20);
*str1 = "Ciao ";
char *str2 = "Marco";
strcat_s(str1, sizeof(str1), str2);
printf("%s", str1);
Now, if I use a predefined array whith a fixed size, strcat_s works perfectly.
How can I use pointers to char instead of array to make it work?
Any other solution or tip will be very appreciated.
Thank you in advance.
You have to copy the strings firstly into the allocated memory. If you like to know the length of a string use strlen(). sizeof() returns the size of the datatype in byte. In your case it is a pointer (4 byte on 32bit, 8 byte on 64bit machines).
The following code should work properly:
char *str1 = (char *)malloc(20);
strcpy(str1,"Ciao ");
char *str2 = (char *)malloc(20);
strcpy(str2,"Marco ");
strcat(str1, str2);
printf("%s", str1);
There are some issues with your code, and there are some general notes on strcat_s.
Your code str1 = (char *)malloc(20); *str1 = "Ciao " does not copy Ciao; *str is a single character at the first position of str, and your expression converts string literal "Ciao " (which is a pointer to a sequence of characters) to some single character (T in this case; surprising, isn't it?). One would need to use strcpy instead. An array, like char buffer[20] = "Ciao ", in contrast, works, because this (special) case is not an assignment but an initialiser of an array.
Your code sizeof(str1) gives you the size of a pointer value, which is probably 4 or 8, and has nothing to do with the actual size of the content or the memory block reserved. One should use strlen instead.
Concerning strcat_s, one should consider that it is not available on all platforms and that you have to be aware of it's special behaviour. For example, if you call strcat_s(somebuffer, 3, "somestrlongerthan3"), which exceeds the maximum length of 3 as provided, somebuffer will be an "empty" string (i.e. the first character will be set to \0.
I'd suggest to use strncat or snprintf instead. See the following variants:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main () {
char c = "Ciao "; // Gives a compiler warning and yields 'T'
#define maxlen 20
// Variant 1: start with initialized buffer, yet no "pointer" and dynamic allocation
char resultBuffer[maxlen] = "Ciao ";
size_t charactersRemaining = maxlen-strlen(resultBuffer)-1;
strncat(resultBuffer, "Marco", charactersRemaining);
// Variant 2: use dynamically allocated buffer and snprintf, with constant "Ciao".
char *resultBuffer2 = malloc(maxlen);
const char* second2 = "Marco";
snprintf(resultBuffer2, maxlen, "Ciao %s", second2);
// Variant 3: use dynamically allocated buffer and snprintf, with probably variable "Ciao" and "Marco"
char *resultBuffer3 = malloc(maxlen);
const char* first3 = "Ciao";
const char* second3 = "Marco";
snprintf(resultBuffer3, maxlen, "%s %s", first3, second3);
return 0;
}
I'm having trouble changing the contents of a variable holding a string. I'm probably thinking of this too literally compared to an int and not as an array. Maybe have to flush array first?
Much thanks.
// declare with maximum size expected +1 (for terminator 0)
char myString1[20] = "Hello"; //declare and assign one line - OK
myString1[20] = "Hello Longer"; // change contents - fails
myString1[] = "Hello Longer"; // change contents - fails
myString1 = "Hello Longer"; // change contents - fails
This is C, not an object oriented language that takes care of copying strings for you. You'll need to use the string library. For example:
char myString1[20] = "Hello";
strncpy(myString1, "Hello Longer", 20);
You need to use a function like strncpy to copy a string.
In C the assigment operator = does not work for arrays. With the only exception of initialisers.
More over this
myString1[20] = "Hello Longer"
is a type mismatch as myString1[20] is a char to which you obviously only can assign a char or something that can be converted to a char.
To trick this you could do:
#include <stdio.h>
struct Str_s
{
char myString[20];
};
int main(void)
{
struct Str_s str1 = {
"Hello"
};
struct Str_s str2 = {
"World"
};
printf("str1='%s'\nstr2='%s'\n", str1.myString, str2.myString);
str2 = str1;
printf("str1='%s'\nstr2='%s'\n", str1.myString, str2.myString);
return 0;
}
This should print:
Hello World
Hello Hello
Obviously the assignment operator works for structs.
I have an array of characters declared as:
char *array[size];
When I perform a
printf("%s", array);
it gives me some garbage characters, why it is so?
http://www.cplusplus.com/reference/clibrary/cstdio/printf/
This url indicates printf takes in the format of: `int printf ( const char * format, ... );
#include <stdio.h>
#include <string.h>
#define size 20
#define buff 100
char line[buff];
int main ()
{
char *array[100];
char *sep = " \t\n";
fgets(line, buff, stdin);
int i;
array[0] = strtok(line, sep);
for (i = 1; i < size; i++) {
array[i] = strtok(NULL, sep);
if (array[i] == NULL)
break;
}
return 0;
}
You declare an array of characters like so:
char foo[size];
You seem to have it mixed up with char *, which is a pointer to a character. You could say
char *bar = foo;
which would make bar point to the contents of foo. (Or, actually, to the first character of foo.)
To then print the contents of the array, you can do one of the following:
// either print directly from foo:
printf("%s", foo);
// or print through bar:
printf("%s", bar);
Note, however, that C performs no initialization of the contents of variables, so unless you specifically set the contents to something, you'll get garbage. In addition, if that garbage doesn't happen to contain a \0; that is, a char with value 0, it will keep on outputting past the end of the array.
Your array is not initialized, and also you have an array of pointers, instead of an array of char's. It should be char* array = (char*)malloc(sizeof(char)*size);, if you want an array of char's. Now you have a pointer to the first element of the array.
Why are we making such a simple thing sound so difficult?
char array[SIZE];
... /* initialize array */
puts(array); /* prints the string/char array and a new line */
/* OR */
printf("%s", array); /* prints the string as is, without a new line */
The char in array after the end of what you want to be your string (ie. if you want your string to read "Hello" that would be the next char after the 'o') must be the terminating NUL character '\0'. If you use a C function to read input that would automatically be appended to the end of your buffer. You would only need to worry about doing it manually if you were individually writing characters to your buffer or something for some reason.
EDIT: As with pmg's comment, the '\0' goes wherever you want the string to end, so if you wanted to shorten your string you could just move it up closer to the front, or to have an empty string you just have array[0] = '\0';. Doing so can also be used to tokenise smaller strings inside a single buffer, just as strtok does. ie. "Part1\0Part2\0Part3\0". But I think this is getting away from the scope of the question.
ie. you wanted to store the first 3 chars of the alphabet as a string (don't know why anyone would do it this way but it's just an example):
char array[4];
array[0] = 'a';
array[1] = 'b';
array[2] = 'c';
array[3] = '\0';
printf("%s\n", array);
If you have something like char array[] = "Hello"; the '\0' is automatically added for you.
char *array[size];
array is not a char * with that, it's more like a char ** (pointer to an array of chars, with is similar to pointer to pointer to char).
If all you need is a C string, either:
char array[size];
and make sure you 0-terminate it properly, or
char *array;
and make sure you properly allocate and free storage for it (and 0-terminate it too).
void reverse(char *str){
int i,j;
char temp;
for(i=0,j=strlen(str)-1; i<j; i++, j--){
temp = *(str + i);
*(str + i) = *(str + j);
*(str + j) = temp;
printf("%c",*(str + j));
}
}
int main (int argc, char const *argv[])
{
char *str = "Shiv";
reverse(str);
printf("%s",str);
return 0;
}
When I use char *str = "Shiv" the lines in the swapping part of my reverse function i.e str[i]=str[j] dont seem to work, however if I declare str as char str[] = "Shiv", the swapping part works? What is the reason for this. I was a bit puzzled by the behavior, I kept getting the message "Bus error" when I tried to run the program.
When you use char *str = "Shiv";, you don't own the memory pointed to, and you're not allowed to write to it. The actual bytes for the string could be a constant inside the program's code.
When you use char str[] = "Shiv";, the 4(+1) char bytes and the array itself are on your stack, and you're allowed to write to them as much as you please.
The char *str = "Shiv" gets a pointer to a string constant, which may be loaded into a protected area of memory (e.g. part of the executable code) that is read only.
char *str = "Shiv";
This should be :
const char *str = "Shiv";
And now you'll have an error ;)
Try
int main (int argc, char const *argv[])
{
char *str = malloc(5*sizeof(char)); //4 chars + '\0'
strcpy(str,"Shiv");
reverse(str);
printf("%s",str);
free(str); //Not needed for such a small example, but to illustrate
return 0;
}
instead. That will get you read/write memory when using pointers. Using [] notation allocates space in the stack directly, but using const pointers doesn't.
String literals are non-modifiable objects in both C and C++. An attempt to modify a string literal always results in undefined behavior. This is exactly what you observe when you get your "Bus error" with
char *str = "Shiv";
variant. In this case your 'reverse' function will make an attempt to modify a string literal. Thus, the behavior is undefined.
The
char str[] = "Shiv";
variant will create a copy of the string literal in a modifiable array 'str', and then 'reverse' will operate on that copy. This will work fine.
P.S. Don't create non-const-qualified pointers to string literals. You first variant should have been
const char *str = "Shiv";
(note the extra 'const').
String literals (your "Shiv") are not modifiable.
You assign to a pointer the address of such a string literal, then you try to change the contents of the string literal by dereferencing the pointer value. That's a big NO-NO.
Declare str as an array instead:
char str[] = "Shiv";
This creates str as an array of 5 characters and copies the characters 'S', 'h', 'i', 'v' and '\0' to str[0], str[1], ..., str[4]. The values in each element of str are modifiable.
When I want to use a pointer to a string literal, I usually declare it const. That way, the compiler can help me by issuing a message when my code wants to change the contents of a string literal
const char *str = "Shiv";
Imagine you could do the same with integers.
/* Just having fun, this is not C! */
int *ptr = &5; /* address of 5 */
*ptr = 42; /* change 5 to 42 */
printf("5 + 1 is %d\n", *(&5) + 1); /* 6? or 43? :) */
Quote from the Standard:
6.4.5 String literals
...
6 ... If the program attempts to modify such an array [a string literal], the behavior is undefined.
char *str is a pointer / reference to a block of characters (the string). But its sitting somewhere in a block of memory so you cannot just assign it like that.
Interesting that I've never noticed this. I was able to replicate this condition in VS2008 C++.
Typically, it is a bad idea to do in-place modification of constants.
In any case, this post explains this situation pretty clearly.
The first (char[]) is local data you can edit
(since the array is local data).
The second (char *) is a local pointer to
global, static (constant) data. You
are not allowed to modify constant
data.
If you have GNU C, you can compile
with -fwritable-strings to keep the
global string from being made
constant, but this is not recommended.