I have a string,
char* str = "HELLO"
If I wanted to get just the E from that how would I do that?
char* str = "HELLO";
char c = str[1];
Keep in mind that arrays and strings in C begin indexing at 0 rather than 1, so "H" is str[0], "E" is str[1], the first "L" is str[2] and so on.
You would do:
char c = str[1];
Or even:
char c = "Hello"[1];
edit: updated to find the "E".
Array notation and pointer arithmetic can be used interchangeably in C/C++ (this is not true for ALL the cases but by the time you get there, you will find the cases yourself). So although str is a pointer, you can use it as if it were an array like so:
char char_E = str[1];
char char_L1 = str[2];
char char_O = str[4];
...and so on. What you could also do is "add" 1 to the value of the pointer to a character str which will then point to the second character in the string. Then you can simply do:
str = str + 1; // makes it point to 'E' now
char myChar = *str;
I hope this helps.
Related
I have a string,
char* str = "HELLO"
If I wanted to get just the E from that how would I do that?
char* str = "HELLO";
char c = str[1];
Keep in mind that arrays and strings in C begin indexing at 0 rather than 1, so "H" is str[0], "E" is str[1], the first "L" is str[2] and so on.
You would do:
char c = str[1];
Or even:
char c = "Hello"[1];
edit: updated to find the "E".
Array notation and pointer arithmetic can be used interchangeably in C/C++ (this is not true for ALL the cases but by the time you get there, you will find the cases yourself). So although str is a pointer, you can use it as if it were an array like so:
char char_E = str[1];
char char_L1 = str[2];
char char_O = str[4];
...and so on. What you could also do is "add" 1 to the value of the pointer to a character str which will then point to the second character in the string. Then you can simply do:
str = str + 1; // makes it point to 'E' now
char myChar = *str;
I hope this helps.
so if I have
char a = 'a';
char b = 'b';
char* combination = a + b;
where the result should be
combination = "ab"
how would I do that? I'm 99% sure that the "+" operator wouldn't work here, but I'm not sure what I should do instead. I am new to C, so sorry for how trivial this question is!
edit** is it possible to this without using an array? meaning without using brackets []
adding 2 chars together to form one char* ... how would I do that?
A direct way to do that since C99 is below which uses a compound literal. #haccks, #unwind
char a = 'a';
char b = 'b';
// v-------------------v--- compound literal
char* combination1 = (char[]) {a, b, '\0'};
printf("<%s>\n", combination1);
combination1 is valid until the end of the block.
I'm 99% sure that the "+" operator wouldn't work here,
OP is correct, + is not the right approach.
is it possible to this without using an array? meaning without using brackets []
This is a curious restrictive requirement.
Code could allocate memory and then assign.
char *concat2char(char a, char b) {
char *combination = malloc(3);
if (combination) {
char *s = combination;
*s++ = a;
*s++ = b;
*s = '\0';
}
return combination;
}
// Sample usage
char *combination2 = concat2char('a', 'b');
if (combination2) {
printf("<%s>\n", combination2);
free(combination2); // free memory when done
}
Using a 3 member struct looks like an option, yet portable code does not rely in s3 being packed.
struct {
char a, b, n;
} s3 = {a, b, '\0' };
// Unreliable to form a string, do not use !!
char* combination3 = (char *) &s3;
printf("<%s>\n", combination);
You need to set up a target array that's at least one element larger than the number of characters in the final string:
char str[3]; // 2 characters plus string terminator
str[0] = a;
str[1] = b;
str[2] = 0; // you'll sometimes see that written as str[2] = '\0'
Neither the + nor = operators are defined for string operations. You'll have to use the str* library functions (strcat, strcpy, strlen, etc.) for string operations.
EDIT
In C, a string is a sequence of character values terminated by a 0-valued byte - the string "hello" is represented by the character sequence {'h', 'e', 'l', 'l', 'o', 0} (sometimes you'll see '\0' instead of plain 0). Strings are stored in arrays of char. String literals like "hello" are stored in arrays of char such that they are visible over the lifetime of the program, but are not meant to be modified - attempting to update the contents of a string literal results in undefined behavior (code may crash, operation may just not succeed, code may behave as expected, etc.).
Except when it is the operand of the sizeof or unary & operators, or is a string literal used to initialize a character array in a declaration, an expression of type "N-element of T" will be converted ("decay") to an expression of type "pointer to T", and the value of the expression will be the address of the first element. So when we're dealing with strings, we're usually dealing with expressions of type char * - however, that does not mean that a char * always refers to a string. It can point to a single character that isn't part of a string, or it can point to a sequence of characters that don't have a 0 terminator.
So, let's start with a string literal like "hello". It will be stored "somewhere" as the array:
+---+---+---+---+---+---+
|'h'|'e'|'l'|'l'|'o'| 0 |
+---+---+---+---+---+---+
When you write something like
char *str = "hello";
the address of the first element of the array that stores "hello" is written to pointer variable str:
+---+ +---+---+---+---+---+---+
str: | | ---> |'h'|'e'|'l'|'l'|'o'| 0 |
+---+ +---+---+---+---+---+---+
While you can read each str[i], you should not write to it (technically, the behavior is undefined). On the other hand, when you write something like:
char str[] = "hello";
str is created as an array, and the contents of the string literal are copied to the array:
+---+---+---+---+---+---+
|'h'|'e'|'l'|'l'|'o'| 0 |
+---+---+---+---+---+---+
+---+---+---+---+---+---+
str: |'h'|'e'|'l'|'l'|'o'| 0 |
+---+---+---+---+---+---+
The array is sized based on the size of the initializer, so it will be 6 elements wide (+1 for the string terminator). If the array is going to hold the result of a concatenation or print operation, then it will need to be large enough to hold the resulting string, plus the 0 terminator, and C arrays do not automatically grow as stuff is added to them. So, if you want to concatenate two 3-character strings together, then the target array must be at least 7 elements wide:
char result[7];
char *foo = "foo";
char *bar = "bar";
strcpy( result, foo ); // copies contents of foo to result
strcat( result, bar ); // appends the contents of bar to result
Just define an array, and arrange the two characters into it, then end it with a final zero-character to form a proper C string:
const char a = 'a';
const char b = 'b';
const char my_string[] = { a, b, '\0' };
printf("The string is '%s'\n", my_string);
In response to comments (which I don't understand, but I'm here to help, heh), here's a twisted way of writing it that does away with the brackets.
uint32_t memory;
char *p = (char *) &memory;
*p++ = a;
*p++ = b;
*p-- = '\0';
printf("the string is '%s'\n", --p);
Note: this code is absurd, but so is the request to not use random parts of the language you're programming in. Do not use this code for anything except reading it here and thinking "wow, that would be soo much better if I could just use braces".
Let's say I have a char pointer called string1 that points to the first character in the word "hahahaha". I want to create a char[] that contains the same string that string1 points to.
How come this does not work?
char string2[] = string1;
"How come this does not work?"
Because that's not how the C language was defined.
You can create a copy using strdup() [Note that strdup() is not ANSI C]
Refs:
C string handling
strdup() - what does it do in C?
1) pointer string2 == pointer string1
change in value of either will change the other
From poster poida
char string1[] = "hahahahaha";
char* string2 = string1;
2) Make a Copy
char string1[] = "hahahahaha";
char string2[11]; /* allocate sufficient memory plus null character */
strcpy(string2, string1);
change in value of one of them will not change the other
What you write like this:
char str[] = "hello";
... actually becomes this:
char str[] = {'h', 'e', 'l', 'l', 'o'};
Here we are implicitly invoking something called the initializer.
Initializer is responsible for making the character array, in the above scenario.
Initializer does this, behind the scene:
char str[5];
str[0] = 'h';
str[1] = 'e';
str[2] = 'l';
str[3] = 'l';
str[4] = 'o';
C is a very low level language. Your statement:
char str[] = another_str;
doesn't make sense to C.
It is not possible to assign an entire array, to another in C. You have to copy letter by letter, either manually or using the strcpy() function.
In the above statement, the initializer does not know the length of the another_str array variable. If you hard code the string instead of putting another_str, then it will work.
Some other languages might allow to do such things... but you can't expect a manual car to switch gears automatically. You are in charge of it.
In C you have to reserve memory to hold a string.
This is done automatically when you define a constant string, and then assign to a char[].
On the other hand, when you write string2 = string1,
what you are actually doing is assigning the memory addresses of pointer-to-char objects. If string2 is declares as char* (pointer-to-char), then it is valid the assignment:
char* string2 = "Hello.";
The variable string2 now holds the address of the first character of the constanta array of char "Hello.".
It is fine, also, to write string2 = string1 when string2 is a char* and string1 is a char[].
However, it is supposed that a char[] has constant address in memory. Is not modifiable.
So, it is not allowed to write sentences like that:
char string2[];
string2 = (something...);
However, you are able to modify the individual characters of string2, because is an array of characters:
string2[0] = 'x'; /* That's ok! */
Here I was trying out the following thing in my code and got the following error---"prog.c:10:8: error: incompatible types when assigning to type ‘char[100]’ from type ‘char *’". Please help and tell me how can I modify my initialisation which is char str[100] to get the right answer
#include <stdio.h>
#include <stdlib.h>
int main()
{
char str[100];
str = "a";
str = str + 1;
str = "b";
str = str + 1;
str = "c";
str = str + 1;
printf("%s", str - 2);
return 0;
}
You have declared an array
char str[100];
By specifying the name of the array you will get the base address of the array which is same as the address of first element.
str="a";
In the above statement, you are trying to assign "a"s (note "a" is string here) address to array base.
The compiler will not allow you to do this. Cos, if you do so, you will lose all the 100 elements.
If you want to assign the first element with the value 'a', then do
str[0] = 'a';
Note that I have used single quote. Remember "Single quote for single char".
You have to use string commands like strcpy/strncpy.
Or you can allocate memory to accomodate the string and use only char pointers, no char array.
while arrays and pointers are closely related in C, they are not entirely the same.
char str[100];
gives you a "const pointer"-like handle to a pre-allocated array of 100 chars. this array will live at a fixed position in memory, so you cannot let str point to some other place.
str="a";
will assign the position of a string "a" to the pointer "str". (which is illegal!).
what you can do, is to assign the values within your array.
char str[100] = {0};
str[0]='a';
str[1]='b';
str[2]='c';
printf("%s", str);
treat str as an array and not as a pointer (str points to a memory address allocated for 100 chars and str[i] accesses the relative memory address of str + i)
char str[100];
str[0]='a';
str[1]='b';
str[2]='c';
str[3]='\0';
printf("%s",str);
if want initialisation a str[100],use this:
char str[100] = "abc";
it only work when we define the str[100] and initialisation str[100] at the same time!
Or you code can work in this way:
char str[100];
str[0] = 'a';
str[1] = 'b';
str[2] = 'c';
str[3] = '\0';
Or :
char str[100];
*str = 'a';
++str;
*str = 'b';
++str;
*str = 'c';
++str;
*str = '\0';
In general when you create an array of characters like this.
char string[100]; //allocate contigious location for 100 characters at compile time
Here string will point to the base address of the contigious location. Assuming memory address starts from 4000 then it would be like
--------------------------------------
|4000|4001|4002|4003|...........|4099|
--------------------------------------
Variable string will point to 4000. To store a value at 4000 you can do *(4000).
Here you can do like
*string='a'; //4000 holds 'a'
*(string+1)='b'; //4001 holds 'b'
*(string+2)='c'; //4002 holds 'c'
Note: Array can be accessed by any of the three forms in c.
string[0] => 0[string] => *(string+0) => points to first element in string array
where
string[0] => *(4000+0(sizeof(char))) => *(4000)
0[string] => *((0*sizeof(char))+4000) => *(4000)
*string => *(4000)
In case of integer array, assuming int takes 4bytes of memory
int count[100]; //allocate contigious location for 100 integers at compile time
Here count will point to the base address of the contigious location. Assuming memory address starts from 4000 then it would be like
--------------------------------------
|4000|4004|4008|4012|...........|4396|
--------------------------------------
variable count will point to 4000. To store a value at 4000 you can do *(4000).
Here you can do like
*count=0; //4000 holds 0
*(count+1)=1; //4004 holds 1
*(count+2)=2; //4008 holds 2
So coming to your code, your objective can be achieved like this.
#include<stdio.h>
#include<stdlib.h>
int main()
{
char str[100];
*str='a';
*(str+1)='b';
*(str+2)='c';
printf("%s",str);
return 0;
}
Output: abc
You persist in using the wrong term, which leads me to believe that is why you couldn't find an answer.
/* 1 */
char str[100] = "a"; //OK
/* 2 */
str = "b"; // error: str is an array
Initialization is what happens when you assign a value to a variable while declaring the variable. This is source code excerpt 1 above.
Assignment is what happens after the variable is declared. You can't assign to a struct or array type. You must address each individual item in the struct/array when assigning values. In code excerpt 2 above, the variable str is assigned the value "b", except that str is an array, so the compiler says there is an error because you can't assign to an array.
Summary:
You can initialize an array, but you cannot assign to it. The difference is in whether the variable was given an explicit value when it was declared. If it was, the variable was initialized. Otherwise, you're trying to assign to an array, which can't be done.
Many, even I when learning c, was confused like you.
Actually you must be clear on this
Difference between `char []` and `char *`
=>char [] is a constant pointer which refers to the same address every time. But its value is not constant
=>char * is a non-constant pointer which can be changed to refer to any string. Its value is also not constant, but if it is assigned the address of a const char * then its value will be const.
Coming to your question
Use methods instring.h
#include<stdio.h>
#include<stdlib.h>
int main()
{
char string[100];
char *str;
*str = 'a';
str = str + 1;
*str = 'b';
str = str + 1;
*str = 'c';
str = str + 1;
printf("%s", str - 2);
return 0;
}
I have a string,
char* str = "HELLO"
If I wanted to get just the E from that how would I do that?
char* str = "HELLO";
char c = str[1];
Keep in mind that arrays and strings in C begin indexing at 0 rather than 1, so "H" is str[0], "E" is str[1], the first "L" is str[2] and so on.
You would do:
char c = str[1];
Or even:
char c = "Hello"[1];
edit: updated to find the "E".
Array notation and pointer arithmetic can be used interchangeably in C/C++ (this is not true for ALL the cases but by the time you get there, you will find the cases yourself). So although str is a pointer, you can use it as if it were an array like so:
char char_E = str[1];
char char_L1 = str[2];
char char_O = str[4];
...and so on. What you could also do is "add" 1 to the value of the pointer to a character str which will then point to the second character in the string. Then you can simply do:
str = str + 1; // makes it point to 'E' now
char myChar = *str;
I hope this helps.