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");
Related
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);
I am trying to take input from a user and I don't the exact length of input so therefore I am using malloc and I am splitting char by space between them and just need to print an array but I am getting warning i.e assignment makes integer from pointer without a cast on the following line:
array[i++] = p;
and my whole program is as follows:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main ()
{
char buf[] ="abc qwe ccd";
int i;
char *p;
char *array=malloc(sizeof(char));
i = 0;
p = strtok (buf," ");
while (p != NULL)
{
array[i++] = p;
p = strtok (NULL, " ");
}
for (i=0;i<3; ++i)
printf("%s\n", array[i]);
return 0;
}
Can anyone please tell me what is wrong with my code.
Thank you.
The following assignment is not right.
array[i++] = p;
array[i++] evaluates to type char. p is of type char*.
That's what the compiler is complaining about.
Judging by the way you are using array, it needs to be of type char**.
char **array = malloc(sizeof(*array)*20); // Make it large enough for your needs.
I guess you wanted to create array of pointers to char instead of array of char.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main (void)
{
char buf[] ="abc qwe ccd";
int i;
char *p;
/* change type of array from char* to char** */
char **array=malloc(sizeof(char*) * sizeof(buf)); /* allocate enough memory */
i = 0;
p = strtok (buf," ");
while (p != NULL)
{
array[i++] = p;
p = strtok (NULL, " ");
}
for (i=0;i<3; ++i)
printf("%s\n", array[i]);
free(array); /* it is good to free whatever you allocated */
return 0;
}
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.
I have a char *p = "abcd", how can I access the elements 'a','b','c','d' using only C(not C++)? Any help would be appreciated .
You can use indexing:
char a = p[0];
char b = p[1];
/* and so on */
Equivalently you can use pointer arithmetic, but I find it less readable:
char a = *p;
char b = *(p+1);
If you really want to surprise someone you can also write this:
char a = 0[p];
char b = 1[p];
/* and so on */
Here, p refers an array of character pointer. You ca use the array indexing to access each variable in that array. The most widely used notation for this is p[n], where n is the n+1th character [element].
example:
for the 1st character, use p[0], 2nd character, use p[1] and so on..
another example:
#include <stdio.h>
int main()
{
char *p="abcd";
for (; *p; p++)
printf("%c\n", *p);
return 0;
}
result is:
a
b
c
d
Use the array subscript operator []. It allows you to access the nth element of a pointer type in the form of p[n].
You can also increment the pointer by using the increment operator ++.
#include <stdio.h>
int main()
{
char *p="abcd";
printf("%c\n", p[0]);
printf("%c\n", p[1]);
printf("%c\n", p[2]);
printf("%c\n", p[3]);
return 0;
}
returns
a
b
c
d
#include <stdio.h>
#include <stdlib.h>
void main()
{
char* str="Hello, World!";
printf("%s\n",str);
}
Output:
Hello, World!
2nd Method:
#include <stdio.h>
#include <stdlib.h>
void main()
{
char* str="Hello";
int n=strlen(str);
for(int i=0;i<n;i++)
{
printf("%c"str[i]);
}
}
Output:
Hello
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,