0

I dont really understand the equilvalent between a string and an array. I know that I'm able to call an element from a string array by using s[i], but what if I want to set that element to another one? For example:

char eng_char[] ={'a','b','c');
string s = "Hello";
s[0] = eng_char[0];

This result in a segmentation error so that means I can't really use a string as freely as a char array right?

So I tried to use another array to replace the string, but then there is another problem in that I can't set the array's length the same as the string since char array[strlen(s)] = {'a'}; doesn't work. How should I go around that?

1
0

There is an intimate relation between an array and a string, the only difference is in the end of string, in the case that we are dealing with is an array of characters and a string, the difference is that in the second case we have a Extra character, the '\ 0' that tells us where our chain ends. This is an important difference because the C language does not allow us to know where an array ends except in the case that we put a "mark" as it happens with the strings, the following declarations are equivalent:

string s = "Hello";
char* s = "Hello";
char s[6] = {"Hello"};
char s[6] = ['H','e','l','l','o','\0'];

However, it is not:

char s[5] = ['H','e','l','l','o'];

Is an array of characters because it lacks the character '\ 0'. There is also an intimate relationship between string and pointers your statement:

s[0] = eng_char[0];

Is really trying to reassign two pointers that are in the stack and are read only, it is not possible to relocate its address unless we declare a variable type pointer to char and reserve memory so you can store a variable, but your statement as how is it a mistake.

About

char array[strlen(s)] = {'a'};

Surely it is that at the time of compilation, the compiler can not know what length has strlen(s), since it is surely not a constant at compile time, hence the error. To solve it we can do something like:

int n = strlen(s);
char array[n];
array[0] = 'a';

I hope this help.

2
  • Yeah since i'm at pset2 I have no really understanding of what a pointer is so look like this is a bit over my head. I will just accept it for now and get back to your explaination later. Thanks – Huynq Apr 30 '17 at 10:57
  • Do not worry about the understanding at this time, suffice it to say that the treatment of the strings in c can be somewhat difficult, it is better not to do strange things with strings at the moment, it is a somewhat advanced concept. – MARS Apr 30 '17 at 11:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .