In the example below if I uncomment the printing of matches[1] and matches[2] in the print_and_modify function it fails(Illegal instruction: 4 on my Mac OS X mavericks).
What confuses me is why matches[0] works fine ? Any help is greatly appreciated.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void print_and_modify(char ***matches) {
printf("%s\n", *matches[0]);
/* printf("%s\n", *matches[1]); */
/* printf("%s", *matches[2]); */
}
int main(int argc, char **argv)
{
char **matches;
matches = malloc(3 * sizeof(char*));
matches[0] = malloc(10 * sizeof(char));
matches[1] = malloc(10 * sizeof(char));
matches[2] = malloc(10 * sizeof(char));
char *test1 = "test1";
char *test2 = "test2";
char *test3 = "test3";
strncpy(matches[0],test1,5);
strncpy(matches[1],test2,5);
strncpy(matches[2],test3,5);
print_and_modify(&matches);
printf("======\n");
printf("%s\n", matches[0]);
printf("%s\n", matches[1]);
printf("%s\n", matches[2]);
}
Please excuse the contrived example. I am trying to learn some C.
It's operator precedence: [] has higher precedence than *, so you need to force the desired precedence:
void print_and_modify(char ***matches) {
printf("%s\n", (*matches)[0]);
printf("%s\n", (*matches)[1]);
printf("%s", (*matches)[2]);
}
Demo.
Note that you do not need to pass a triple pointer, unless you wish to modify the allocated array itself. If you pass a double pointer, you would be able to modify the content of the individual strings, and also replace strings with other strings by de-allocating or re-allocating the char arrays.
Related
I am getting a segmentation fault on the following code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void init_test(char ***test) {
*test = malloc(2 * sizeof(char *));
*test[0] = malloc(3);
*test[1] = malloc(3);
strcpy(*test[0], "12");
strcpy(*test[1], "13");
}
int main()
{
char **test = NULL;
init_test(&test);
printf("1: %s, 2: %s", test[0], test[1]);
printf("Hello World");
return 0;
}
I have couple of different variations of this, but I am not sure how to correctly initialize a char** in a different function.
It's a matter of operator precedence. The expression *test[0] is equal to *(test[0]), not (*test)[0] as you seem to expect.
The array index operator has higher precedence than the dereference operator. You need to add parenthesis:
(*test)[0] = malloc(3);
(*test)[1] = malloc(3);
strcpy((*test)[0], "12");
strcpy((*test)[1], "13");
When I allocate an array using malloc, is there a way to only free the first element(s) of the array?
A small example:
#include <stdlib.h>
#include <string.h>
int main() {
char * a = malloc(sizeof(char) * 8);
strcpy(a, "foo bar");
// How I would have to do this.
char * b = malloc(sizeof(char) * 7);
strcpy(b, a+1);
free(a);
free(b);
}
Is there a way to free just the first char of a, so that I can use the rest of the string using a+1?
If you want to remove the first character of a, you could use memmove() to move the remainder of the characters in the string to the left by 1, and you could use realloc() to shrink the allocation if desired:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char * a = malloc(sizeof(char) * 8);
strcpy(a, "foo bar");
puts(a);
size_t rest = strlen(a);
memmove(a, a+1, rest);
/* If you must reallocate */
char *temp = realloc(a, rest);
if (temp == NULL) {
perror("Unable to reallocate");
exit(EXIT_FAILURE);
}
a = temp;
puts(a);
free(a);
return 0;
}
Update
#chux has made a couple of good points in the comments.
First, instead of exiting on a failure in realloc(), it may be better to simply continue without reassigning temp to a; after all, a does point to the expected string anyway, the allocated memory would just be a little larger than necessary.
Second, if the input string is empty, then rest will be 0. This leads to problems with realloc(a, rest). One solution would be to check for rest == 0 before modifying the string pointed to by a.
Here is a slightly more general version of the above code that incorporates these suggestions:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char *s = "foo bar";
char *a = malloc(sizeof *a * (strlen(s) + 1));
strcpy(a, s);
puts(a);
size_t rest = strlen(a);
/* Don't do anything if a is an empty string */
if (rest) {
memmove(a, a+1, rest);
/* If you must reallocate */
char *temp = realloc(a, rest);
if (temp) {
a = temp;
}
}
puts(a);
free(a);
return 0;
}
Is there a way to free just the first char of a
No. You can not free the first character of a because it is of char type. Only pointer returned by malloc family function can be freed.
You can do this though.
char * a = malloc(sizeof(char) * 8);
strcpy(a, "foo bar");
char * b = malloc(strlen(a));
strcpy(b, a+1);
free(a);
There's a function. It is add_lexem and adds an element (char *) in the end of specified array and. If no memory left, it allocates some extra memory (100 * sizeof(char *)). That function causes segfault, which is the problem.
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
void add_lexem(char **lexems, int *lexemsc, int *lexem_n, const char *lexem)
{
if (*lexem_n >= *lexemsc) {
lexems = realloc(lexems, sizeof(char *) * (*lexemsc + 100));
*lexemsc += 100;
}
char *for_adding = malloc(sizeof(char) * strlen(lexem));
strcpy(for_adding, lexem);
lexems[*lexem_n] = for_adding;
(*lexem_n)++;
}
int main(void)
{
char **D = malloc(sizeof(char *) * 2);
int lexemsc = 2;
int lexem_n = 0;
add_lexem(D, &lexemsc, &lexem_n, "MEOW");
printf("%s\n", D[0]);
add_lexem(D, &lexemsc, &lexem_n, "BARK");
printf("%s\n", D[1]);
// in this place lexem_n becomes equal lexemsc
add_lexem(D, &lexemsc, &lexem_n, "KWARK");
printf("%s\n", D[2]);
return 0;
}
The output must be
MEOW
BARK
KWARK
but it is
MEOW
BARK
Segmentation fault (core dumped)
You're passing your lexeme parameter by value, when it should be by address:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
// removed unused void ccat(char *str, char c)
void add_lexem(char ***lexems, int *lexemsc, int *lexem_n, const char *lexem)
{
if (*lexem_n >= *lexemsc) {
*lexems = realloc(*lexems, sizeof(char *) * (*lexemsc + 100));
*lexemsc += 100;
}
char *for_adding = malloc(sizeof(char) * strlen(lexem)+1);
strcpy(for_adding, lexem);
(*lexems)[*lexem_n] = for_adding;
(*lexem_n)++;
}
int main(void)
{
char **D = malloc(sizeof(char *) * 2);
int lexemsc = 2;
int lexem_n = 0;
add_lexem(&D, &lexemsc, &lexem_n, "MEOW");
printf("%s\n", D[0]);
add_lexem(&D, &lexemsc, &lexem_n, "BARK");
printf("%s\n", D[1]);
// in this place lexem_n becomes equal lexemsc
add_lexem(&D, &lexemsc, &lexem_n, "KWARK");
printf("%s\n", D[2]);
return 0;
}
Output
MEOW
BARK
KWARK
Note: Triple indirection (i.e. a 3-start-programming) is not something to enter into lightly, though it actually fits what you appear to be trying to do here. Read the above code carefully and make sure you understand how it works.
Edit: added terminator space for added string. (don't know why I missed it, since it was what everyone else seemed to be catching on first-review, duh).
Note: See #wildplasser's answer to this question. Honestly it is the best way to do this, as it tightens the relationship between the string pointer array and the magnitude of said-same. If it is possible to retool your code to use that model, you should do so, and in-so-doing select that answer as the the "correct" solution.
Alternative to avoid the three-star-programming: put everything you need inside a struct:
struct wordbag {
size_t size;
size_t used;
char **bag;
};
void add_lexem(struct wordbag *wb, const char *lexem)
{
if (wb->used >= wb->size) {
wb->bag = realloc(wb->bag, (wb->size+100) * sizeof *wb->bag );
wb->size += 100;
}
wb->bag[wb->used++] = strdup(lexem);
}
The main problem is that you are passing D to the function by value: the assignment
lexems = realloc(...);
has no effect on D. In cases when realloc performs reallocation, D becomes a dangling pointer, so dereferencing it becomes undefined behavior.
You need to pass D by pointer in the same way that you pass lexemsc and &lexem_n, so that the realloc's effect would be visible inside the main function as well.
In addition, your add_lexem does not allocate enough memory for the string being copied: strlen does not count the null terminator, so these two lines
char *for_adding = malloc(sizeof(char) * strlen(lexem));
strcpy(for_adding, lexem);
write '\0' one byte past the allocated space.
The problem may come from :
char *for_adding = malloc(sizeof(char) * strlen(lexem));
strcpy(for_adding, lexem);
try char *for_adding = malloc(sizeof(char) * (strlen(lexem)+1)); to leave some space for the '\0 character.
Edit : and #WhozCraig seems to be right !
Bye,
I would like to reallocate an array of string with a function. I write a very simple program to demonstrate here. I expect to get the letter "b" to be output but I get NULL.
void gain_memory(char ***ptr) {
*ptr = (char **) realloc(*ptr, sizeof(char*) * 2);
*ptr[1] = "b\0";
}
int main()
{
char **ptr = malloc(sizeof(char*));
gain_memory(&ptr);
printf("%s", ptr[1]); // get NULL instead of "b"
return 0;
}
Thank you very much!
The [] operator has high priority than *, so change the code like this will work right.
(*ptr)[1] = "b";
P.S. "\0" is unnecessary.
You should put parentheses around *ptr in gain_memory:
(*ptr)[1] = "b\0";
You're not allocating any memory for the actual strings in your array of strings, you need to do something like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void gain_memory(char ***ptr, int elem) {
*ptr = (char**)realloc(*ptr, 2*elem*sizeof(char*));
(*ptr)[1] = "b";
}
int main()
{
//How many strings in your array?
//Lets say we want 10 strings
int elem = 10;
char **ptr = malloc(sizeof(char*) * elem);
//Now we allocate memory for each string
for(int i = 0; i < elem; i++)
//Lets say we allocate 255 characters for each string
//plus one for the final '\0'
ptr[i] = malloc(sizeof(char) * 256);
//Now we grow the array
gain_memory(&ptr, elem);
printf("%s", ptr[1]);
return 0;
}
if i dupe topic i really sorry, i searched for it with no result here.
I have code
void split(char* str, char* splitstr)
{
char* p;
char splitbuf[32];
int i=0;
p = strtok(str,",");
while(p!= NULL)
{
printf("%s", p);
sprintf(&splitstr[i],"%s",p);
i++;
p = strtok (NULL, ",");
}
}
How can i use proper sprintf to put the splited words by strtok to string array?
Can i somehow avoid breaklines created by strtok?
I am programming in ANSI C. I declared array splitstr and str the same way.
char* splitstr;//in main char splitstr[32];
Thanks for help.
edit:
i would like do something like this:
INPUT (it is a string) > "aa,bbb,ccc,ddd"
I declare: char tab[33];
OUTPUT (save all items to array of strings if it is even possible) >
tab[0] is "aa"
tab[1] is "bbb"
...
tab[3] is "ddd" but not "ddd(newline)"
edit2 [18:16]
I forgot add that the data string is from reading line of file. That's why i wrote about "ddd(newline)". I found after that the new line was also shown by strtok but as another item. By the way all answers are good to think over the problem. Few seconds ago my laptop has Broken (i dont know why the screen gone black) As soon as i take control over my pc i will check codes. :-)
Give this a shot:
#include <stdlib.h>
#include <string.h>
...
void split(char *str, char **splitstr)
{
char *p;
int i=0;
p = strtok(str,",");
while(p!= NULL)
{
printf("%s", p);
splitsr[i] = malloc(strlen(p) + 1);
if (splitstr[i])
strcpy(splitstr[i], p);
i++;
p = strtok (NULL, ",");
}
}
And then, in main:
#define MAX_LEN ... // max allowed length of input string, including 0 terminator
#define MAX_STR ... // max allowed number of substrings in input string
int main(void)
{
char input[MAX_LEN];
char *strs[MAX_STR] = {NULL};
...
split(input, strs);
...
}
Some explanations.
strs is defined in main as an array of pointer to char. Each array element will point to a string extracted from the input string. In main, all that's allocated is the array of pointers, with each element initially NULL; the memory for each element will be allocated within the split function using malloc, based on the length of the substring. Somewhere after you are finished with strs you will need to deallocate those pointers using free:
for (i = 0; i < MAX_STR; i++)
free(strs[i]);
Now, why is splitstr declared as char ** instead of char *[MAX_STR]? Except when it is the operand of the sizeof or & operators, or is a string literal being used to initialize another array in a declaration, an array expression will have its type implicitly converted from N-element array of T to pointer to T, and the value of the expression will be the location of the first element in the array.
When we call split:
split(input, strs);
the array expression input is implicitly converted from type char [MAX_LENGTH] to char * (T == char), and the array expression strs is implicitly converted from type char *[MAX_STRS] to char ** (T == char *). So splitstr receives pointer values for the two parameters, as opposed to array values.
If I understand correctly, you want to save the strings obtained by strtok. In that case you'll want to declare splitstr as char[MAX_LINES][32] and use strcpy, something like this:
strcpy(splitstr[i], p);
where i is the ith string read using strtok.
Note that I'm no ansi C expert, more C++ expert, but here's working code. It uses a fixed size array, which may or may not be an issue. To do anything else would require more complicated memory management:
/* Not sure about the declaration of splitstr here, and whether there's a better way.
char** isn't sufficient. */
int split(char* str, char splitstr[256][32])
{
char* p;
int i=0;
p = strtok(str,",");
while(p) {
strcpy(splitstr[i++], p);
p = strtok (NULL, ",");
}
return i;
}
int main(int argc, char* argv[])
{
char input[256];
char result[256][32];
strcpy(input, "aa,bbb,ccc,ddd");
int count = split(input, result);
for (int i=0; i<count; i++) {
printf("%s\n", result[i]);
}
printf("the end\n");
}
Note that I supply "aa,bbb,ccc,ddd" in and I get {"aa", "bbb", "ccc", "ddd" } out. No newlines on the result.