C Language: Change the contents of a string array - c

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.

Related

Modify a character pointer string array (char * string[])

I've been giving an... interesting... task. I've been asked to modify a character array using a pointer.
I'm aware that:
*char = "something"; //is a literal and cannot be modified.
char[] = "something"; //can be modified
But what about:
main.c
------
static char* stringlist01[] =
{
"thiy iy a ytring",
"this is also a string, unlike the first string",
"another one, not a great one, and not really like the last two.",
"a third string!",
NULL,
};
int main()
{
int ret = 9999;
printf("////TEST ONE////\n\n");
ret = changeLetterInString(stringlist01[0]);
printf("Return is: %d\n\n", ret);
printf("Stringlist01[0] is now: %s\n", stringlist01[0]);
}
AND
changeLetterInString.c
----------------------
int changeLetterInString(char *sentence)
{
if (sentence != NULL)
{
// TODO
// Need to change "thiy iy a ytring"
// into "this is a string"
// and save into same location so
// main.c can see it.
}
success = 0; // 0 is Good
return success;
}
So far, I've tried:
for (char* p = sentence; *p; ++p)
{
if (*p == 'y')
{
*p = 's';
}
}
And I've tried:
sentence[0] = 't'
sentence[1] = 'h'
sentence[2] = 'i'
sentence[3] = 's' // and so on...
But neither work.
Any help and/or insight would be greatly appreciated.
There are subtle differences between the two notations:
char string[] = "Hello World";
// vs
char* string = "Hello World";
They look similar enough, right? However they are different. The first one is an array of characters, whereas the second one is a pointer to an array of characters.
By default, any string literal will always be const. No way around it. Trying to modify a string literal will usually result in a segfault.
Your code contains an array of pointers to an array of characters. Since you contain pointer references to constant string literals, you cannot modify them. In order to modify them, you need to convert them into an array instead, like how it's done in the first example. This will transform the string literal to an array of characters, that can be modified, rather than being a pointer to memory which cannot be modified.
char strs[][] = {
"Hello",
"World"
}; // transforms the string literals into character arrays
strs[0][0] = 'X'; // valid
Whereas this would not compile, and caused undefined behaviour
char* strs[] = {
"Hello",
"World",
};
strs[0][0] = 'X'; // trying to modify a pointer to a constant string literal, undefined

How To Assign char* to an Array variable

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;
}

How to convert constant char pointer to lower case in C?

I've a function which receives a const char* and I want to convert it to lowercase. But I get the error:
error: array initializer must be an initializer list or string literal
I tried to copy the string variable to another array so that I could lower case it. But I think I've got something confused.
This is my function:
int convert(const char* string)
{
char temp[] = string;
temp = tolower(temp); //error is here
//do stuff
}
I'm struggling to understand what this error means, could someone help in explaining it?
tolower takes a single character and returns it in lowercase.
Even if it didn't, arrays aren't assignable. Arrays and pointers are not the same thing.
You presumably want to do something like:
char *temp = strdup(string); // make a copy
// adjust copy to lowercase
unsigned char *tptr = (unsigned char *)temp;
while(*tptr) {
*tptr = tolower(*tptr);
tptr++;
}
// do things
// release copy
free(temp);
Make sure you understand the difference between the heap and the stack, and the rules affecting string literals.
First of all, tolowertakes char or int, not string.
but even if you passed char, your code wouldn't work, because this error array initializer must be an initializer list or string literal ,means you have to initialize it using one of the following methods:
char arr[4] = {'h', 'e', 'y','\0'}; // initializer list
char arr[4] = "hey"; // string literal
char arr[] = "hey"; // also a string literal
char arr[4];
arr[0] = 'h';
arr[1] = 'e';
arr[2] = 'y';
arr[4] = '\0';
Please note that, tolower() takes a character and not a string:
int tolower ( int c );
Also you are trying to copy the string from string to temp[] variable. There in no overloading of the = operator in C to copy the string into char array.
Now about your error:
error: array initializer must be an initializer list or string literal
It says that the array must be initialized via an list of initial individual items or you can directly assign a string literal.
E.g:
char temp[] = "Hi";
char temp[] = {'H','i','\0'};
Also, check your statement:
temp = tolower(temp);
Here the return type of tolower() is int that you are assigning it to the array temp which is improper.
You can use the following snippet using strlwr():
int convert(const char* string)
{
char *temp= malloc(strlen(string)+1);
strcpy(temp,string);
strlwr(temp);
//do your stuff
}

string literal in c

Why is the following code illegal?
typedef struct{
char a[6];
} point;
int main()
{
point p;
p.a = "onetwo";
}
Does it have anything to do with the size of the literal? or is it just illegal to assign a string literal to a char array after it's declared?
It doesn't have anything to do with the size. You cannot assign a string literal to a char array after its been created - you can use it only at the time of definition.
When you do
char a[] = "something";
it creates an array of enough size (including the terminating null) and copies the string to the array. It is not a good practice to specify the array size when you initialize it with a string literal - you might not account for the null character.
When you do
char a[10];
a = "something";
you're trying to assign to the address of the array, which is illegal.
EDIT: as mentioned in other answers, you can do a strcpy/strncpy, but make sure that the array is initialized with the required length.
strcpy(p.a, "12345");//give space for the \0
You can never assign to arrays after they've been created; this is equally illegal:
int foo[4];
int bar[4];
foo = bar;
You need to use pointers, or assign to an index of the array; this is legal:
p.a[0] = 'o';
If you want to leave it an array in the struct, you can use a function like strcpy:
strncpy(p.a, "onetwo", 6);
(note that the char array needs to be big enough to hold the nul-terminator too, so you probably want to make it char a[7] and change the last argument to strncpy to 7)
Arrays are non modifiable lvalues. So you cannot assign to them. Left side of assignment operator must be an modifiable lvalue.
However you can initialize an array when it is defined.
For example :
char a[] = "Hello World" ;// this is legal
char a[]={'H','e','l','l','o',' ','W','o','r','l','d','\0'};//this is also legal
//but
char a[20];
a = "Hello World" ;// is illegal
However you can use strncpy(a, "Hello World",20);
As other answers have already pointed out, you can only initialise a character array with a string literal, you cannot assign a string literal to a character array. However, structs (even those that contain character arrays) are another kettle of fish.
I would not recommend doing this in an actual program, but this demonstrates that although arrays types cannot be assigned to, structs containing array types can be.
typedef struct
{
char value[100];
} string;
int main()
{
string a = {"hello"};
a = (string){"another string!"}; // overwrite value with a new string
puts(a.value);
string b = {"a NEW string"};
b = a; // override with the value of another "string" struct
puts(b.value); // prints "another string!" again
}
So, in your original example, the following code should compile fine:
typedef struct{
char a[6];
} point;
int main()
{
point p;
// note that only 5 characters + 1 for '\0' will fit in a char[6] array.
p = (point){"onetw"};
}
Note that in order to store the string "onetwo" in your array, it has to be of length [7] and not as written in the question. The extra character is for storing the '\0' terminator.
No strcpy or C99 compund literal is needed. The example in pure ANSI C:
typedef struct{
char a[6];
} point;
int main()
{
point p;
*(point*)p.a = *(point*)"onetwo";
fwrite(p.a,6,1,stdout);fflush(stdout);
return 0;
}

Memory access violation. What's wrong with this seemingly simple program?

This is a quick program I just wrote up to see if I even remembered how to start a c++ program from scratch. It's just reversing a string (in place), and looks generally correct to me. Why doesn't this work?
#include <iostream>
using namespace std;
void strReverse(char *original)
{
char temp;
int i;
int j;
for (i = 0, j = strlen(original) - 1; i < j; i++, j--)
{
temp = original[i];
original[i] = original[j];
original[j] = temp;
}
}
void main()
{
char *someString = "Hi there, I'm bad at this.";
strReverse(someString);
}
If you change this, which makes someString a pointer to a read-only string literal:
char *someString = "Hi there, I'm bad at this.";
to this, which makes someString a modifiable array of char, initialized from a string literal:
char someString[] = "Hi there, I'm bad at this.";
You should have better results.
While the type of someString in the original code (char*) allows modification to the chars that it points to, because it was actually pointing at a string literal (which are not permitted to be modified) attempting to do any modification through the pointer resulted in what is technically known as undefined behaviour, which in your case was a memory access violation.
If this isn't homework, the C++ tag demands you do this by using the C++ standard library:
std::string s("This is easier.");
std::reverse(s.begin(), s.end());
Oh, and it's int main(), always int main(), dammit!
You're trying to modify a string literal - a string allocated in static storage. That's undefiend behaviour (usually crashes the program).
You should allocate memory and copy the string literal there prior to reversing, for example:
char *someString = "Hi there, I'm bad at this.";
char* stringCopy = new char[strlen( someString ) + 1];
strcpy( stringCopy, someString );
strReverse( stringCopy );
delete[] stringCopy;//deallocate the copy when no longer needed
The line
char *someString = "Hi there, I'm bad at this.";
makes someString point to a string literal, which cannot be modified. Instead of using a raw pointer, use a character array:
char someString[] = "Hi there, I'm bad at this.";
You can't change string literals (staticly allocated). To do what you want, you need to use something like:
int main()
{
char *str = new char[a_value];
sprintf(str, "%s", <your string here>);
strReverse(str);
delete [] str;
return 0;
}
[edit] strdup also works, also strncpy... i'm sure there's a variety of other methods :)
See sharptooth for explanation.
Try this instead:
#include <cstring>
void main()
{
char someString[27];
std::strcpy( someString, "Hi there, I'm bad at this." );
strReverse( someString );
}
Better yet, forget about char * and use <string> instead. This is C++, not C, after all.
When using more strict compiler settings, this code shouldn't even compile:
char* str = "Constant string";
because it should be constant:
const char* str = "Now correct";
const char str[] = "Also correct";
This allows you to catch these errors faster. Or you can just use a character array:
char str[] = "You can write to me, but don't try to write something longer!";
To be perfectly safe, just use std::string. You're using C++ after all, and raw string manipulation is extremely error-prone.

Resources