Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have here some sample code that has what I think is needed to solve my problem.
Basicaly I need to store inside an array that has a variable amount of entries a variable amount of reasons for it. Is this array[5].b[3] not allowed? Is there any alternative for it?
Thanks in advance
typedef struct {
int a;
char *reasons;
}t_a;
f() {
int space=10,spaceReasons=5;
t_a *array;
array=NULL;
array=realloc(array,sizeof(t_a)*space);
array[5].reasons=realloc(array[5].reasons,sizeof(char)*spaceReasons);
fgets (array[5].reasons[3]),300, stdin);
free(array);
}
Here's a working example:
#include <stdlib.h>
#include <stdio.h>
typedef struct {
int a;
char* reasons;
} t_a;
int main(void) {
int space = 10, spaceReasons = 5;
t_a* array = NULL;
array = realloc(array, sizeof(t_a) * space);
for (int i = 0; i < space; i++) {
array[i].reasons = NULL;
array[i].reasons = realloc(array[i].reasons, sizeof(char) * spaceReasons);
// fill with fgets
fgets (array[i].reasons, spaceReasons, stdin);
}
// print results
for (int i = 0; i < space; i++) {
printf("%s\n", array[i].reasons);
}
// first free all reasons
for (int i = 0; i < space; i++) {
free(array[i].reasons);
}
// then free array
free(array);
}
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
Im trying to define and initialize an array of strings using a function, but, the function is causing segmentation fault while allocating memory for each of the pointers.
Please find below the minimal reproducible version of the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define COL 100
#define ROW 10
int init_arr(char ***arr_ptr) {
*arr_ptr = malloc(sizeof(char *) * ROW);
for(int temp_iter = 0; temp_iter < ROW; ++temp_iter) {
*arr_ptr[temp_iter] = malloc(COL + 1);
strncpy(*arr_ptr[temp_iter], "MY_STRING_IS_THIS", COL);
}
return 0;
}
int main() {
char **arr_of_str = NULL;
init_arr(&arr_of_str);
for(int temp_iter = 0; temp_iter < ROW; ++temp_iter) {
printf("\nData: %s", arr_of_str[temp_iter]);
}
}
This code works fine when the function is split into 2 where the first function defines it and 2nd one initializes it.
The problem lies here *arr_ptr[temp_iter], first dereference(in his case a subscription) that was applied was from box brackets, and then from asterix. What you want to do is separate these dereferences, so that asterix is applied first and the from box brackets, like this:
int init_arr(char*** arr_ptr) {
*arr_ptr = (char**) malloc(sizeof(char *) * ROW);
for(int temp_iter = 0; temp_iter < ROW; ++temp_iter) {
(*arr_ptr)[temp_iter] = (char*) malloc(COL + 1);
strncpy((*arr_ptr)[temp_iter], "MY_STRING_IS_THIS", COL);
}
return 0;
}
Also, you need to cast the pointer from malloc into appropriate one, since the malloc always returns void*, and you are dereferencing void pointer later on.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I am facing issue copying data to void pointer array through for loop. I am not allowed to use double pointer.
I am trying someting like this:
for(i=0;i<9;i++){
array + i = i;
}
but I cant just do this, and I know that,
I am trying to do it like this
memcpy(
array+i,
i,
s
);
I have already allocated memory:
My actual code is some thing like this:
if(v->e_type==V_INT){
// printf("%p ",v->e_array+v->no_e);
memcpy(
v->e_array+v->no_e,
new_val,
v->e_sz
);
}
If you have something like this:
int *x = malloc(sizeof(int)*4);
You can put values in it with pointer arithmetic:
for(int i = 0; i < 4; i++) {
*(x+i) = i; // or *(x+1) = 0; for example
}
Or simply:
for(int i = 0; i < 4; i++) {
x[i] = i;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
This code need to save friends in some array of array(pointer to pointer) and by the length of the names do realloc (build exactly dynamic place for the strings of each of them) and than prints the string and the length and free everything.
So the code work when i debugging but when I running it with CTR+f5 it's crashed after the fgets of the first string. also all the free loops and the free function doesn't work me here, but if remove it the debugging still work and the CTR+f5 still don't work. help someone?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LENGTH 20
int main(void)
{
int i = 0, j = 0,friends=0;
char str[LENGTH];
printf("Hello bro,how U doin'?\nTell me how many friends do you have?\n");
scanf("%d",&friends);
char** friendBook = (char**)malloc(sizeof(char)*friends);
if (friendBook)
{
getchar();
for (i = 0; i < friends; i++)
{
*(friendBook+ i) = malloc(LENGTH*sizeof(char));
}
for (i = 0; i < friends; i++)
{
printf("Enter friend number: %d\n", i + 1);
fgets(str, LENGTH, stdin);
str[strcspn(str, "\n")] = 0;
*(friendBook + i) = (char*)realloc(*(friendBook+i),(sizeof(char)*strlen(str))); // dynamic memory for every string(name)
if (*(friendBook + i))
{
strcpy(*(friendBook+i),str);
}
}
for (i = 0; i < friends; i++)
{
printf("Friend: %s\tLength of friend name %d\n", *(friendBook + i), strlen(*(friendBook + i)));
}
}
for (i = 0; i <friends; i++)
{
free(*(friendBook+i));
}
free(friendBook);
system("PAUSE");
return 0;
}
Take the string "Hello". strlen ("Hello") = 5. But to store it, you need SIX bytes, not five, because there is a zero byte at the end that doesn't get counted by strlen.
PS. Undefined behaviour when you try to print strlen with %d format. Can crash, print nonsense, or worse. Use %zd. Turn all warnings on in your compiler and fix them.
PS. BLUEPIXY spotted a much worse problem...
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Just a disclaimer: I am a complete noob when it comes to C programming and this might be embarrassingly easy but I can't think it out myself and haven't found anything otherwise helpful. Anyways, this program below is supposed to put names (last, first) and ages into arrays and then alphabetize them. The problem I have is creating a sort of parallel array to match ages with their respective names after sorting them alphabetically. Does anyone have any suggestions? I was thinking of somehow tying the age array into my defined functions, but I still can't wrap my head around that either. Thanks in advance!
#include <stdio.h>
#include <string.h>
#define NAME_LENGTH 50
#define MAX_NAMES 50
int alpha_first(char *list[], int min_sub, int max_sub);
void select_sort_str(char *list[], int n);
int
main(void)
{
int i = 0;
int numpeople;
char names[MAX_NAMES][NAME_LENGTH] = { 0 };
char ages[MAX_NAMES][NAME_LENGTH] = { 0 };
char skip_line;
char *alpha[MAX_NAMES] = { 0 };
printf("Enter number of people <0..50>\n> ");
scanf("%d", &numpeople);
do
{
scanf("%c", &skip_line);
}
while (skip_line != '\n');
for(i = 0; i < numpeople; ++i)
{
printf("Enter name %d (lastname, firstname) ", i+1);
gets(names[i]);
printf("Enter age %d: ", i+1);
gets(ages[i]);
}
for(i = 0; i < numpeople; ++i)
{
alpha[i] = names[i];
select_sort_str(alpha, numpeople);
}
printf("\n\n%-30s\n\n", "Original List");
for (i = 0; i < numpeople; ++i)
printf("%-30s\n", names[i]);
printf("\n\n%-30s\n\n", "Alphabetical Order");
for (i = 0; i < numpeople; ++i)
printf("%-30s\n", alpha[i]);
return 0;
}
int
alpha_first(char *list[],
int min_sub, int max_sub)
{
int first, i;
first = min_sub;
for (i = min_sub + 1; i <= max_sub; ++i)
if (strcmp(list[i], list[first]) < 0)
first = i;
return (first);
}
void
select_sort_str(char *list[], int n)
{
int fill, index_of_min;
char *temp;
for (fill=0; fill<n-1; ++fill)
{
index_of_min = alpha_first(list, fill, n - 1);
if (index_of_min != fill)
{
temp = list[index_of_min];
list[index_of_min] = list[fill];
list[fill] = temp;
}
}
}
Use a structure:
typedef struct
{
char *first_name;
char *last_name;
int age;
} person;
When you create your array, create an array of person; Create a new person, fill in its fields, add it to your array. Now you have all of the data you need in one nice little package.
Most problems in computer science are solved by introducing an extra level of indirection.
In this case, observe that select_sort_str() is sorting an array of pointers to strings. Suppose instead you construct an array of index values, initialised to 0..numpeople-1, and then you sort those indexes into the order of the corresponding names. So, in alpha_first(), as well as taking char* list[] let it also take int index[] and the comparison becomes:
if (strcmp(list[index[i]], list[index[first]]) < 0)
and similarly select_sort_str(), in which you don't swap the entries in the list[] but in the index[]. Then to read the entries in alpha order, you use the extra level of indirection:
names[index[i]]
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
Well, my question is pretty simple, yet i've been stuck for quite a while. I'd like to write a program that takes two arrays as arguments, and then write the letters in it without duplicates, in order of appearance.
example :
$ ./a.out bulwark blue
bulwarke
$ ./a.out fresh feeling
freshling
$ ./a.out final01 test02
final01tes2
I tried a few ways, but can't figure how to do it without malloc. The tricky thing is, I cannot use malloc, the only authorized function is "write"
P.S : Sorry for my bad English
Use an auxiliary array to indicate which letter has already been used:
void func(char arr1[],char arr2[])
{
int hash[256] = {0};
for (int i=0; arr1[i]!=0; i++)
{
unsigned char letter = (unsigned char)arr1[i];
if (hash[letter] == 0)
{
hash[letter] = 1;
printf("%c",letter);
}
}
for (int i=0; arr2[i]!=0; i++)
{
unsigned char letter = (unsigned char)arr2[i];
if (hash[letter] == 0)
{
hash[letter] = 1;
printf("%c",letter);
}
}
printf("\n");
}
Note: this code assumes that each of the input strings (arr1 and arr2) is terminated with a 0 character.
Just keep track what you have printed. The follow will work just fine for char, because there are so few of them. Keeping track of unicode chars with an array that is long enough for all possible values would be mad. In such case inserting identifiers to a hash would probably be better option, but since unicode was not part of the consideration the following should be good enough.
#include <stdio.h>
int main(int argc, char **argv)
{
char arr[256] = { 0 };
int i, j;
for (i = 1; i < argc; i++)
for (j = 0; argv[i][j]; j++)
if (!arr[argv[i][j]]) {
arr[argv[i][j]] = 1;
printf("%c", argv[i][j]);
}
putchar('\n');
return 0;
}