I am writing insertion sort using strings. I have char arrays like:
char array1[4] = {'a', 'b', 'c', '\0'};
char array2[4] = {'b', 'd', 'e', '\0'};
And I need to use this operation:
char string[2];
string[1] = array1;
string[2] = array2;
Is it possible ?
Because in insertion sort I need a string.
This is the insertion code:
char* insertionsort(char* a, int n) {
int k;
for (k = 1; k < n; ++k) {
int key = a[k];
int i = k - 1;
while ((i >= 0) && (key < a[i])) {
a[i + 1] = a[i];
--i;
}
a[i + 1] = key;
}
return a;
}
So I need to write this operation :
char string [2];
string[1] = array1;
string[2] = array2;
Is it possible ?
Short answer: no, it's not. Arrays are not assignable. You can use strcpy to copy the elements from one string to another, but in this case that won't work either -- you've defined string as an array of 2 chars, but you're trying to assign an entire array of chars to each of those.
It's not entirely clear that it's what you want, but one possibility would be:
char *string[2];
string[1] = array1;
string[2] = array2;
In this case, string is an array of two pointers to char, and the assignments set those to point to the first character of each of your previously defined strings.
Since you've tagged this as both C and C++, I'll add a bit about that: this is written as very much C code. If you're actually using C++, you probably want something more like:
std::string[2] = {"abc", "bde"};
Even in C, I'd prefer to initialize and use string constants where they make sense:
char array1[] = "abc";
char array2[] = "bde";
char *string[] = {array1, array2};
Or even just:
char const *string[] = {"abc", "bde"};
char array1[4] = {'a', 'b', 'c', '\0'}; // same as char *array1 = "abc";
char array2[4] = {'b', 'd', 'e', '\0'}; // same as char *array2 = "bde";
char *string [2]; // an array of 'pointers to chars' / array of strings
string[1] = array1; // this will work
string[2] = array2; // this will work
Of course not. Just remember,
char ary[4] = {'a', 'b', 'c', '\0'}; //define an array of char
When you use ary like this:
char string[2];
string[0] = ary;
ary degenerates from the name of an array to a pointer! So, what you do above is assigning a pointer to a char type, and which will lead to a type warning when compiling.
This is very important in C!
And you can fix it like this:
char *string[2]; //an array of pointers to char
string[1] = array1; //correct
string[2] = array2;
Related
I need the length of an array. One way works perfectly, one gives the wrong answer, and one doesn't compile.
This doesn't compile:
size_t len = sizeof(array) / sizeof(array[0]);
This counts only first 4 letters:
size_t len = sizeof(array) / sizeof(char);
And len = 12 works.
I really don't understand this so some hint is greatly appreciated.
const char array[] = {'t', 'h', 'i', 's', 'i', 's', 'm', 'y', 't', 'e', 'x', 't', '\0'};
void count_chars(const char *array, unsigned int *counts)
{
size_t len = 12;
for(size_t i = 0; i < len; i++){
counts[(int)array[i]]++;
}
}
You cant determine the size of the passed array inside function. You need to pass size as an additional parameter.
const char array[] = {'t', 'h', 'i', 's', 'i', 's', 'm', 'y', 't', 'e', 'x', 't', 0};
void count_chars(const char *arr, unsigned int *counts, size_t size)
{
for(size_t i = 0; i < size; i++)
counts[(unsigned)arr[i]]++;
}
int main(void)
{
int cnt[sizeof(array[0]) * (1 << CHAR_BIT)];
count_chars(array, cnt, sizeof(array) / sizeof(array[0]));
}
You need to cast to unsigned (not int) because char values can be negative.
What you are trying to do is actually impossible in C. The general rule of thumb is to calculate the length of the array in the function where the array is declared and pass it to the function. This is due to the fact that C doesn't pass the entire array when calling a function but rather just the base address as a pointer variable. To breakdown your approaches and the reason they do/don't work are:
size_t len = sizeof(array) / sizeof(array[0]);
This the commonly accepted approach but the prerequisite is that array must be declared in the same scope not be a pointer.
size_t len = sizeof(array) / sizeof(char);
As array is pointer a type variable and therefore has the size 4(atleast on 32-bit machines) dividing by sizeof(char) is 1 resulting in the answer 4
size_t len = 12;
This works as it's hard coded.
An easy solution in your case could be use:
size_t len = strlen(array)
as mentioned assuming you can guarantee that the last element will be 0 or '\0'. In this situation you could also simply modify the looping condition to:
for(int i = 0; array[i] != 0; i++) {
...
}
Hope I could clarify your doubt
size_t len = sizeof(array) / sizeof(array[0]);
This is general approach for getting the length of an array. However, this will not work inside count_chars function because array is defined as local variable (a pointer) inside the API. And if it is the case, the result will be 13 (not 12 as you mentioned) because it count also the \0 at the end.
For string of characters, it is possible to use strlen. As in the question, you expected result = 12 so this might be your right solution. However, this will not work if there is some \0 value in the middle because it will find first string terminator (\0).
In C if you want to get length of Null Terminated Strings you have to check for NULL \0 and count characters.
Check here how strlen method works.
//Custom Strlen function.
size_t my_strlen(const char *str)
{
register const char *s;
for (s = str; *s; ++s);
return(s - str);
}
Strlen Source
To count length of Arrays (General) like Int,Float,Double you can use below method.
size_t int_arr_len = sizeof(int_arr) / sizeof(int_arr[0]);
size_t float_arr_len = sizeof(float_arr) / sizeof(float_arr[0]);
Full Source Code below
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char char_arr[] = {'t', 'h', 'i', 's', 'i', 's', 'm', 'y', 't', 'e', 'x', 't', 0}; // `\0` Null Terminated.
const int int_arr[] = {10, 20, 30, 40, 50};
const float float_arr[] = {1.5f, 2.5f, 3.5f, 4.5f, 5.5f};
//Custom Strlen function.
size_t my_strlen(const char *str)
{
register const char *s;
for (s = str; *s; ++s);
return(s - str);
}
int main()
{
//Array length for Strings(Char array. Null Terminated. `\0`)
size_t char_arr_len1 = strlen(char_arr);
size_t char_arr_len2 = my_strlen(char_arr);
//Array length for General arrays like Int,Float,Double...etc
size_t int_arr_len = sizeof(int_arr) / sizeof(int_arr[0]);
size_t float_arr_len = sizeof(float_arr) / sizeof(float_arr[0]);
//Print length of arrays.
printf("char_arr_len1: %zu\n", char_arr_len1);
printf("char_arr_len2: %zu\n", char_arr_len2);
printf("int_arr_len: %zu\n", int_arr_len);
printf("float_arr_len: %zu\n", float_arr_len);
return 0;
}
I am new to c .
When i try to do
char a = 'h';
Char b = 'j';
Strcat(a,b);
I get an error because a and b must be two strings .
So how can i do this ?
For the sake of completion here's a list of possible solutions:
gsamaras (esiest for your case):
char str[] = {a, b, '\0'};
Through an array:
char* string = (char*)malloc(3);
string[0] = 'a';
string[1] = 'b';
string[2] = '\0';
Generically:
char* str1 = "a";
char* str2 = "b";
size_t str1_len = 2;
size_t str2_len = 2;
char* new_str = (char*)malloc(str1_len - 1 + str2_len);
memcpy(new_str, str1, str1_len - 1);
memcpy(new_str + str1_len, str2, str2_len);
strcat() is a method used to concatenate strings. In your cases you have characters, so you shouldn't use this method.
Instead, you can create the string yourself, like this for example:
char str[] = {a, b, '\0'};
Take these two characters as string and then use strcat() function.
char a[] = "h";
char b[] = "j";
strcat(a,b);
printf("%s",a);
How to concatenate two characters and store the result in a variable?
For example, I have 3 characters 'a', 'b' and 'c' and I need to join them together and store them in an array and later use this array as a string:
#include <stdio.h>
#include <string.h>
char n[10];
main ()
{
// now I want insert them in an array
//ex: n = { a + b + c }
}
There are many ways, the following 2 methods have exactly the same results: (using your code as a starting point.)
#include <stdio.h>
#include <string.h>
int main(void)
{
//Given the following
char a = 'a';
char b = 'b';
char c = 'c';
// assignment by initializer list at time of creation
char n1[10] = {a,b,c};
//usage of a string function
char n2[10] = {0}; //initialize array
sprintf(n2, "%c%c%c", a, b, c);
return 0;
}
Both result in a null terminated char arrays, or C strings.
Simply:
char a = 'a', b = 'b', c = 'c';
char str[4];
str[0] = a;
str[1] = b;
str[2] = c;
str[3] = '\0';
Or, if you want str to be stored on the heap (e.g. if you plan on returning it from a function):
char *str = malloc(4);
str[0] = a;
...
Any introductory book on C should cover this.
An assignment similar to that can only be done when the char array is declared using array initialiation with a brace-enclosed list:
char a = 'a', b = 'b', c = 'c';
char n[10] = {a, b, c};
After the declaration you can't do it like this because a char array is not a modifiable lvalue:
n = {a, b, c}; //error
To insert characters in an array that has been previously initialized, you need to either insert them one by one as exemplified in another answer, or use some library function like sprintf.
sprintf(n, "%c%c%c", a, b, c);
In both of my examples the char array will be null terminated by the compiler so you can use it as a string, if you assign the characters one by one, make sure to place a null terminator at the end ('\0'), only then will you have a propper string.
How do I convert something like:
const char phrase[] = "this is my phrase";
into something like:
char a[0] = "this";
char a[1] = "is";
char a[2] = "my";
char a[3] = "phrase";
Can I use pointers to access the words rather than the characters in a char array?
I want to use an array of char pointers where each pointer in the array is pointing to a char in another char array, therefore, I would be able to print the char array through the pointers.
char city[14] = {'D', 'u', 'b', 'a', 'i'};
char *charPointers[100] = {0};
for(size_t i = 0;city[i] != '\0'; i++)
charPointers[i] = &city[i];
printf("\ncity = ");
for(size_t i = 0; *charPointers != 0; i++)
//printf("%c", *(charPointers[i]));
putchar(*charPointers[i]);
Is charPointers an array of pointers or simply a string ?
If it's a string, then how can I use an array of pointers such that each pointer is pointing to a char?
What's an elegant way to achieve what I want? (preferably using pointer arithmetic)
charPointers is an array of pointers; it is categorically not simply a string.
Since it isn't a string, your second question is moot.
Your loop condition is incorrect; you need to write:
for (size_t i = 0; charPointers[i] != 0; i++)
//printf("%c", *(charPointers[i]));
putchar(*charPointers[i]);
putchar('\n');
You're testing whether the first pointer is null; it isn't. You need to check the current pointer on each iteration. The loop below might help you understand what's going on, too:
for (size_t i = 0; charPointers[i] != 0; i++)
printf("%zd [%s]\n", i, charPointers[i]);
This code:
#include <stdio.h>
int main(void)
{
char city[14] = {'D', 'u', 'b', 'a', 'i'};
char *charPointers[100] = {0};
for(size_t i = 0;city[i] != '\0'; i++)
charPointers[i] = &city[i];
printf("city = ");
for (size_t i = 0; charPointers[i] != 0; i++)
putchar(*charPointers[i]);
putchar('\n');
for (size_t i = 0; charPointers[i] != 0; i++)
printf("%zd [%s]\n", i, charPointers[i]);
return 0;
}
produces this output:
city = Dubai
0 [Dubai]
1 [ubai]
2 [bai]
3 [ai]
4 [i]
charPointer is an array of pointers to char. A pointer to an array of char would be char (*p)[100];.
Your code is near correct, here is the not-segfaulting version :
char city[14] = {'D', 'u', 'b', 'a', 'i', '\0'};
char* charPointers[100] = {0};
size_t i =0;
for(i = 0; city[i] != '\0'; i++)
charPointers[i] = city + i;
charPointers[i] = city + i; // Don't forget to add the \0 at the end !
printf("\ncity = ");
for(i = 0; *charPointers[i] != '\0'; i++)
printf("%c", *charPointers[i]);
I don't really know what you want to do, but the code above is storing a pointer to each character of the string city in each element of charPointers.
However, if you want to store a pointer to existing string in charPointers (for instance, each element of charPointers points to a city name), here would be the correct code:
char* cityNames[NB_CITY];
char* city = "Dubai";
cityNames[0] = city;
printf("%s\n", cityNames[0]); // gives "Dubai"
charPointers is clearly an array of pointers to characters. The array city is a string (as pointed out in a comment) since you've specified a length of 14 but only provided 5 actual characters. The rest are set to zero which will terminate the string.
A much clearer way to get the same result would be:
const char *city = "Dubai";
Your loop over *charPointers is strange, since it treats *charPointers as a character, when it's really a pointer.
Perhaps you meant:
for(size_t i = 0; charPointers[i] != NULL; ++i)
printf("%s\n", charPointers[i]);
I want to use an array of char pointers where each pointer in the array is pointing to a char in another char array
Why? There is never a reason why you would want to do this, in real world programming.
therefore, I would be able to print the char array through the pointers
Indeed. That's handy if your program is too fast and too effective.
Is charPointers an array of pointers or simply a string?
It's an array of pointers.
What's an elegant way to achieve what I want?
There is no elegant way to "use an array of char pointers where each pointer in the array is pointing to a char in another char array". This is obfuscation and it fills no purpose except making your code slow and unreadable.
Sane, elegant code would look like this:
const char city [] = {'D', 'u', 'b', 'a', 'i', '\0'};
printf("City = ");
print_str(city);
...
void print_str (const char* str)
{
while(*str != '\0')
{
putchar(*str);
str++;
}
}