Related
I have two arrays of strings called name and subject. I want to have another array of strings whose elements are obtained by concatenating the string of the first array with the string with the same index of the other array. The new array should be the output of a function.
Here I give a code sample, but I am unable to compile due to getting errors.
I have also seen this question but I am unable to use it.
Can anyone give me a hint on how to solve this without dynamic allocation and also with dynamic allocation?
#include <stdio.h>
#include <string.h>
const int MAX = 4;
char* concancate_string(char* name,char* subject);
int main () {
char* name[] = {
"michel",
"sam",
"roy",
"romi"
};
char* subject[] = {
"physics",
"math",
"chemistry",
"biology"
};
char* p[];
p=concancate_string(name,subject);
for ( int i = 0; i < MAX; i++) {
printf("name and subject[%d] = %s\n", i, name[i] );
}
return 0;
}
char* concancate_string(char* name,char* subject)
{
for ( int i = 0; i < MAX; i++) {
strcat(name[i]," : ");
strcat(name[i],subject[i]);
}
return name;
}
resulted output array:
{
"michel : physics",
"sam : math",
"roy : chemistry",
"romi : biology"
}
Here's my attempt with dynamic allocation:
char **concancate_string(const char *name[], const char *subject[], size_t n) {
char **destin = malloc(n * sizeof *destin);
for (int i = 0; i < n; i++) {
destin[i] = malloc(strlen(name[i]) + strlen(subject[i]) + 3 + 1); // add space for " : " and terminating '\0'
sprintf(destin[i], "%s : %s", name[i], subject[i]);
}
return destin;
}
Remember to all free(destin[k]) and free(destin).
See code running on https://ideone.com/3Qb7v1
First of all, this declaration doesn't work:
char* p[]; // how much stack memory should the compiler reserve?
p=concancate_string(name,subject); // can't assign to an array
Instead, do this:
char **p = concancate_string(name, subject); // you can assign to pointers, though
Also this signature is wrong:
char* concancate_string(char* name,char* subject);
It's taking and returning arrays of char*, not single char*, so it should be:
char **concancate_string(char **name, char **subject);
Furthermore, you can't concatenate to a pointer that you assigned a string literal to. Those point to your program's binary, which is readonly. Instead, the function should look like this:
char **concancate_string(char **name, char **subject)
{
char **pointers = malloc(MAX * sizeof(char*));
for (int i = 0; i < MAX; i++) {
pointers[i] = malloc(strlen(name[i]) + strlen(subject[i]) + 4);
sprintf(pointers[i], "%s : %s", name[i], subject[i]);
}
return pointers;
}
Note how we're allocating an array for the pointers, then allocate memory for every single string, then use sprintf to assemble them (you could also use strcpy and strcat, of course).
Finally, your print is wrong. You make your p, but instead of printing that, you print name. It should instead be:
printf("name and subject[%d] = %s\n", i, p[i]);
And when you're done, the memory should be freed:
for (int i = 0; i < MAX; i++) {
free(p[i]);
}
free(p);
My suggestion to you is to write your programs one part of the time, only starting with the next part when the last part is tested and works well. If you just write the entire program without testing and then it doesn't work because there's errors all over the place, it becomes much harder to find them.
If you can assume a maximum length of each string then there is no need to use dynamic allocation. In the example below (which compiles and run) I assumed each string has a length of 100 (99 usable characters plus the \0 character).
So I defined an array using your MAX constant and 100 as char result[MAX][100] = {0};. {0} initializes all the elements to 0 (this initialization works only with 0. Then I passed this new array to the function. Note that you were defining the function parameter as char* name which means a string: you want to pass an array of strings: I redefined as concancate_string(char* name[], char* subject[], char out[MAX][100]): note the difference.
Strings are simply concatenated with strcat. There is also another function strncat which allows you to specify the max number of char to copy.
#include <stdio.h>
#include <string.h>
const int MAX = 4;
int concancate_string(char* name[], char* subject[], char out[MAX][100]);
int main () {
char result[MAX][100] = {0} ;
char* name[] = {
"michel",
"sam",
"roy",
"romi"
};
char* subject[] = {
"physics",
"math",
"chemistry",
"biology"
};
int p=concancate_string(name, subject, result);
for ( int i = 0; i < MAX; i++) {
printf("%s\n", result[i] );
}
return 0;
}
int concancate_string(char* name[], char* subject[], char out[MAX][100])
{
for ( int i = 0; i < MAX; i++) {
strcat(out[i], name[i]);
//printf("%s\n", out[i] );
strcat(out[i], " : ");
//printf("%s\n", out[i] );
strcat(out[i], subject[i]);
//printf("%s\n", out[i] );
}
retur
I am trying to write a program for my class but I can't get started because I don't know how to access the function's argument elements. A char array is passed into the function like this:
RPN_calculator(input1)
where input1 is a pointer to an array and the function starts like this
int RPN_calculator(const char** input)
{
int n = strlen(*input);
printf("LENGTH OF INPUT: %d\n", n);
return 0;
}
I was trying to find the length of the array and then iterate through the array but anything I've tried does not print the right length of the array and I can't seem to figure out how to access any of the elements of 'input' (the print statement was just for debugging)
EDIT:
even when I calculate n as:
int n = sizeof(*input)/sizeof(*input[0]);
it doesn't work
I hope this source code will help you with the issue. It is a simple example program that demonstrates how to access any of the strings character by character and also how to find the size of the strings.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NUMBER_OS_CHAR_STRINGS 5
/* Here input is a pointer to an array of strings */
const char *input[NUMBER_OS_CHAR_STRINGS] = {
"ONE", /*string0. string[0][0] = 'O' -> first element of string0 - O
string[0][1] = 'N' -> second element of string0 - N
string[0][2] = 'E' -> third element of string0 - E */
"TWO", /*string1*/
"THREE", /*string2*/
"FOUR", /*string3*/
"FIVE", /*string4*/
};
int RPN_calculator(const char **input);
void itterate (const char **input, int choosen_string);
int main(void) {
int string_to_itterate = 0;
RPN_calculator(input);
printf("Select the string which you would like to print char by char:\n");
scanf("%d", &string_to_itterate);
itterate(input, string_to_itterate);
return(0);
}
int RPN_calculator(const char** input)
{
int i;
for (i = 0; i < NUMBER_OS_CHAR_STRINGS; i++)
{
int n = strlen(input[i]);
printf("LENGTH OF INPUT: %d\n", n);
}
return 0;
}
/*Simple example function which itterates throught the elements of a chossen string and prints them
one by one.*/
void itterate (const char **input, int choosen_string)
{
int i;
/*Here we get the size of the string which will be used to define the boundries of the for loop*/
int n = strlen(input[choosen_string]);
for (i = 0; i < n; i++)
{
printf("The %d character of string[%d] is: %c\n",i+1, choosen_string, input[choosen_string][i] ); /*Here we print each character of the string */
}
return;
}
I have an array of values:
array1[] = {1, 32, 4, 12};
Which I want to store as a string of hexadecimal representations of each value (with format "%02x") :
string = "0120040c";
I can print the string using a for loop just fine:
for (int i=0;i<array_size;++i)
printf("%02x", array[i]);
But haven't been able to assign the resulting string to a char array. How can I do this?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *join(int n, char *a[n]){
int i;
size_t lens[n], len=1;
for(i=0;i<n;++i)
len += (lens[i] = strlen(a[i]));
char *cat = malloc(len);
char *p = cat;
for(i=0;i<n;++i){
memcpy(p, a[i], lens[i]+1);
p += lens[i];
}
return cat;
}
int main(void){
char *array1[] = {"a", "p", "p", "l", "e"};
char *string;
int n = sizeof(array1)/sizeof(*array1);
string = join(n, array1);
puts(string);
free(string);
return 0;
}
Apparently you want to create a string showing the values in an array as hexadecimals. This can be done, relatively easily by looping over the string, and with some snprintf magic. But first, let's establish what we need to know, and how to obtain that info:
Why size is the array
How many chars will each value take up in our target string
How are we accessing the array, as an array or a pointer (ie: is it passed to a function or not)
If you have a compiler that supports C99 or C11, you can use a VLA. First, let's assume that you have an array (And not a pointer):
const char * format = "%02x";//each value will be 2 chars + terminating 0
int array[] = { 123, 32, 4354, 544};
size_t arr_len = sizeof array/ sizeof *array;//get the nr of elements in the array
char string[arr_len*2 + 1];//nr of array elements *2 (chars) + terminating 0
for (int i=0;i<arr_len;++i)
{//this is where the magic happens:
snprintf(string + (i*2), 3, format, array[i]);
}
printf("The full hex string is: %s\n", string);
Now let's look at this bit: snprintf(string + (i*2), 3, format, array[i]);
I'm using the string array, as if it were a pointer, as if string contained a memory address pointing to string[0]. By adding i*2 to it, I'm telling snprintf that the target memory to where it should write the output starts at the N-th element of the array. On the first iteration, i is 0, so string + 0*2 == string + 0 == string, the second time, it's string + (1*2) == string + 2 == &string[2]. Effectively, concatenating the output.
Then, I pass 3 to snprintf, telling the function that the max length of the output is 3 chars (including the terminating \0 char). That's a perfect fit for the 2 hex chars + \0 coming from our format "%02x". Then it's a simple matter of passing array[i] to add the hex value to the end of the string.
Great, now what if array is passed to a function, and/or you don't have VLA's? same as above, with a few differences. You'll have to compute and pass the length of the array to the function (computation method shown above). You'll also have to allocate the memory for the string yourself (and free it), which shouldn't be too difficult either:
char * get_hex_string(int *arr, size_t arr_len)
{
char * string = malloc((arr_len * 2 + 1) * sizeof *string);//the sizeof *string is optional
if (string == NULL)
return NULL;
string[0] = '\0';//clear first char, just in case
for (int i=0;i<arr_len;++i)
snprintf(string + i*2, 3, "%02x", arr[i]);//same as before
string[arr_len*2] = '\0';//optional, just a habit of mine
return string;//return string
}
int main( void )
{
int array[] = {12, 32, 54, 1, 6};
char *as_string = get_hex_string(array, sizeof array/sizeof *array);
if (as_string == NULL)
{
fprintf(stderr, "Failed to get hex-string\n");
exit( EXIT_FAILURE );
}
printf("Hex-string: %s\n", as_string);
free(as_string);//optional here, but good habit
return EXIT_SUCCESS;
}
Demo
It's a bit unclear why you've written array2[0], that implies that array2 should be an array of strings, declared like so:
char array2[N][M];
Where N is at least 1 and M is at least 6 to hold "apple\0".
If you just meant that array2 should be a single string, declared like so:
char array2[32];
for instance, then you can create that by copying the characters from array1 and then ending the string by putting in the '\0' character at the end:
memcpy(array2, array1, 5);
array2[5] = '\0';
At this point, doing e.g. printf("'%s'\n", array2); will print 'apple'.
If I have understood correctly you then the definition of a two-dimensional array will look like
char a[M][N] = { "apple" };
where M and N some integral constants that specifies sizes of the array. (In C you may use also Varaiable Length Arrays if the compiler supports them)
Or if you want to copy the first array in the first element of a two dimensional array defined like above then you need to write
memcpy( a[0], array1, 5 );
a[0][5] = '\0';
If array1 would contain a zero terminated string then you could use strcpy instead of memcpy
Note
I think you mean for example
array1[0] = 'a';
instead of
array1[0] = "a"
If so then the code can look like
#include <stdio.h>
#include <string.h>
int main(void)
{
char array1[5];
char array2[10][6];
array1[0] = 'a';
array1[1] = 'p';
array1[2] = 'p';
array1[3] = 'l';
array1[4] = 'e';
memcpy( array2[0], array1, 5 );
array2[0][5] = '\0';
printf( "array2[0] = %s\n", array2[0] );
return 0;
}
Otherwise if array1 is a two-dimensional array itself then you should use standard function strcat and the code could look like
#include <stdio.h>
#include <string.h>
int main(void)
{
char array1[5][2] = { "a", "p", "p", "l", "e" };
char array2[10][6] = { { '\0' } };
for ( int i = 0; i < 5; i++ ) strcat( array2[0], array1[i] );
printf( "array2[0] = %s\n", array2[0] );
return 0;
}
In both cases the output will be
apple
Or if the second array is a one dimensional array then you can write
#include <stdio.h>
#include <string.h>
int main(void)
{
char array1[5][2] = { "a", "p", "p", "l", "e" };
char string[6] = { '\0' };
for ( int i = 0; i < 5; i++ ) strcat( string, array1[i] );
printf( "string = %s\n", string );
return 0;
}
This should work for you:
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 6
int main() {
char array1[MAX_SIZE];
char array2[1][MAX_SIZE];
array1[0] = 'a';
array1[1] = 'p';
array1[2] = 'p';
array1[3] = 'l';
array1[4] = 'e';
//...
array1[MAX_SIZE-1] = '\0';
strcpy(array2[0], array1);
array2[0][MAX_SIZE-1] = '\0';
printf("%s", array2[0]);
return 0 ;
}
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++;
}
}
Hi friends i am new to C, trying to understand it.
I have these two char arrays one is initialized and other is just declared, i just wanted to copy elements from array state to arr and print it. It compiles, but prints a garbage value....
please help me
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int i = 0;
char *arr[3];
char *state[3] = {"California", "Oregon", "Washington", "Texas"};
for(i=0; i<3; i++)
{
arr[i] = state[i];
printf("%s\n",arr+i);
}
arr[0] = state[0];
printf("%s\n",arr[0]);
system("pause");
return 0;
}
Printing arr+i is probably not what you want. Instead, you want arr[i], that is one indirection level deeper.
To be concrete, a[b] is exactly the same as *(a+b).
first of all, i think that the way you've initialized state is wrong. it should have at most 3 items, but you have given 4 items ("Texas"). change it to:
char *state[3] = {"California", "Oregon", "Washington"};
in addition to that, the arr+i gives the address of the i-th pointer of arr. in order to print the string that the i-th pointer in arr points to, use * like this *(arr+i), which is similar to arr[i].
moreover, please don't use system("pause");; getchar() does it much better.
First, you have taken the size of both the array as 3, which is wrong. You have four string values in the state array so correct array size will be 4.
char *arr[4];
char *state[4] = {"California", "Oregon", "Washington", "Texas"};
Second, you are printing the address of array "arr" insisted of value.
// wrong way
for (i = 0; i < 3; i++)
{
arr[i] = state[i];
printf("%s\n", arr + i);
}
Third, you are accessing the first value of array "arr[0]" in a wrong way. Here you have to use pointer to access value.
// wrong way
printf("%s\n", arr[0]);
Here is the correct way to copy values from one array to another by using pointer.
#include<stdio.h>
int main(int argc, char *argv[])
{
int i = 0;
char *arr[4];
char *state[4] = {"California", "Oregon", "Washington", "Texas"};
for(i = 0; i < 4; i++)
{
arr[i] = state[i];
printf("%s\n", *(arr + i));
}
arr[0] = state[0];
printf("%s\n", *(arr));
system("pause");
return 0;
}