how to use append() in c? [closed] - c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 months ago.
Improve this question
I'm trying to add the index of a value, if it is ==1, to a list in C. Is this even possible? How would I go about it?
this is the general code I have so far:
int ones[256];
int index;
for (index = 0; index < sizeof(input); i++) {
if (input & 1 == 1) {
count = count + 1;
ones.append() = index;
}

You have to implement append yourself. You probably want to wrap that implementation using an array struct that tracks both the length and the elements (optionally you can track capacity and over-allocate). A basic mockup looks like this:
#include <stdio.h>
#include <stdlib.h>
void append(int** array, size_t* length, int element) {
*array = (int*) realloc(*array, 1 + *length);
(*array)[*length] = element;
*length += 1;
}
void print(int* array, size_t len) {
printf("Array(%lu): ", len);
for (size_t i = 0; i < len; i++) {
printf("%d ", array[i]);
}
printf("\n");
}
int main() {
int* array = (int*)malloc(0);
size_t len = 0;
print(array, len);
append(&array, &len, 0);
append(&array, &len, 1);
append(&array, &len, 2);
print(array, len);
}

Related

How to read and print unique coordinates(x,y) from an array of struct in C [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have an array of structures containing an index and coordinates (x, y e.g 0,0: 1,2: 0,0), I want to print only unique indexes and coordinate points points from this array, so far I have
#define MAX_NUMBER_OF_POINTS 1000
struct fixation_point_type {
int id_number;
int x;
int y;
};
struct fixation_point_type fixation_point_types[MAX_NUMBER_OF_POINTS];
{
cordinate[N].id_number;
cordinate[N].x;
cordinate[N].y;
N++;
The expected output should be a unique index and coordinates.
If the the coordinates are:
715 242
695 241
695 241
the expected output will be:
715 242
695 241
To be honest not tested.
#define MAX_NUMBER_OF_POINTS 500
typedef struct
{
int id_number;
int x;
int y;
}fixation_point_type ;
fixation_point_type sf[MAX_NUMBER_OF_POINTS];
int find_in_array(int (*arr)[2], int x, iny y, size_t size)
{
int result = 0;
for(size_t index = 0; index < size; index++)
{
if(*arr[0] == x && *arr[1] == y)
{
result = 1;
break;
}
arr++;
}
return result;
}
void print_distinct(fixation_point_type *fp, size_t elements)
{
size_t arrsize = 0;
int fd[MAX_NUMBER_OF_POINTS][2];
for(size_t index = 0; index < MAX_NUMBER_OF_POINTS; index++)
{
if(!find_in_array(&fd[0], sf[index].x, sf[index].y, arrsize))
{
fd[arrsize][0] = fp[index].x;
fd[arrsize][1] = fp[index].y;
arrsize++;
printf("Index: %d, X:%d, Y:%d\n", fp[index].id_number, fp[index].x, fp[index].y);
}
}
}
Here is a function to print unique coordinates in the array of structures:
size_t print_coordinates(const fixation_point_type *array, size_t size) {
size_t i, j, count = 0;
for (i = 0; i < size; i++) {
for (j = 0; j < i; j++) {
if (array[i].x == array[j].x && array[i].y == array[j].y) {
/* found a duplicate */
break;
}
}
if (i == j) {
/* no duplicates: print the coordinates */
printf("%d %d\n, array[i].x, array[i].y);
count++;
}
}
return count;
}

Getting segmentation fault for large values [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
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.
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.
Improve this question
Below program is crashing with segmentation for large n (n > 200), can you please help me out here.
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
struct node {
char name[16];
char num[8];
};
int main() {
int n, i,j;
struct node *hash;
scanf("%d",&n);
hash = (struct node *) malloc(n * sizeof(struct node));
for (i=0; i<n ; i++) {
scanf("%s %s", (hash + (i *sizeof(struct node)))->name,
(hash + (i *sizeof(struct node)))->num);
}
for (i=0; i<n ; i++) {
printf("%s=%s\n",(hash + (i *sizeof(struct node)))->name,
(hash + (i *sizeof(struct node)))->num);
}
return (0);
}
When you add an integer to a pointer, the compiler performs the pointer arithmetic. So hash + i is translated by the compiler into something like (char*)hash + i * sizeof(struct node). The offset in bytes is calculated for you, and then applied in bytes.
Your code is therefore equivalent to
(char*)hash + i * sizeof(struct node) * sizeof(struct node)
This will reach beyond the array boundary very fast, invoking undefined behavior.
As the comments summarized, either use (hash + i) or the more concise (in my opinion) hash[i].
#include <stdio.h>
#include <stdlib.h>
struct node {
char name[16];
char num[8];
};
int main(void) {
size_t n;
if (scanf("%zu", &n) != 1) {
return 1;
}
struct node *hash = malloc(n * sizeof *hash);
if (hash == NULL) {
return 1;
}
for (size_t i = 0; i < n; i++) {
if (scanf("%15s %7s", hash[i].name, hash[i].num) != 2) {
free(hash);
return 1;
}
}
for (size_t i = 0; i < n; i++) {
printf("%s %s\n", hash[i].name, hash[i].num);
}
free(hash);
}

Understanding function pointers and insertion-sort in C [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am trying to implement an insertion sort with parameters very similar to the built in qsort in C, but I'm struggling to find the right approach as I am failing in completely grasping function pointers. How would I go about rewriting this as an insertion sort (with function pointers?)
static void sort(char *array, size_t size, int (*cmp)(void*,void*), int
begin, int end) {
if (end > begin) {
void *pivot = array + begin;
int l = begin + size;
int r = end;
while(l < r) {
if (cmp(array+l,pivot) <= 0) {
l += size;
} else if ( cmp(array+r, pivot) > 0 ) {
r -= size;
} else if ( l < r ) {
swap(array+l, array+r, size);
}
}
l -= size;
swap(array+begin, array+l, size);
sort(array, size, cmp, begin, l);
sort(array, size, cmp, r, end);
}
}
void qsort(void *array, size_t nitems, size_t size, int (*cmp)(void*,void*)) {
sort(array, size, cmp, 0, nitems*size);
}
Many thanks!
You simply have to replace the comparison operator in the insertion sort algorithm by your compare function. Your function insertionSort should look like this.:
void insertionSort(void *array, size_t nitems, size_t size, int (*cmp)(void*,void*))
{
size_t i, j;
for ( i = 1; i < nitems; i++ )
{
j = i;
while ( j > 0 && cmp( (char*)array+j-1, (char*)array+j ) > 0 )
// ^^^ call of cmp instead of operator >
{
swap( (char*)array+j-1, (char*)array+j, size );
j--;
}
}
}
I used this source for the Insertion Sort algorithm.
If you like to pass the swap function as a paramter too, you can do it like this:
void insertionSort(void *array, size_t nitems, size_t size, int (*cmp)(void*,void*), void (*swapdata)(void*,void*,size_t))
{
size_t i, j;
for ( i = 1; i < nitems; i++ )
{
j = i;
while ( j > 0 && cmp( (char*)array+j-1, (char*)array+j ) > 0 )
{
swapdata( (char*)array+j-1, (char*)array+j, size );
j--;
}
}
}

C passing a pointer of an array to a function getting different results [closed]

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 7 years ago.
Improve this question
I'm fairly new to C and having trouble with this code.
int * choose(int * got, int n_chosen, int len, int max_types, int n, int states, int * comb){
int i;
if (n_chosen == len) {
if (!got) return NULL;
for (i = 0; i < len; i++){
comb[len*n + i] = times[got[i]];
printf("%d\n",comb[len*n + i] );
}
++n;
return NULL;
}
for (i = 0; i < max_types; i++) {
if (got) got[n_chosen] = i;
choose(got, n_chosen + 1, len, max_types, n, states, comb);
}
return comb;
}
In the main I have the following code:
int num_states = (int) pow(4.0,(double)lab->color_count);
int num = lab->room_count * num_states;
int chosen[4];
int * combinations = malloc(sizeof(int)*num_states*lab->color_count);
choose(chosen, 0, lab->color_count, 4, 0, num_states, combinations);
int a, b;
for(b=0; b < num_states; ++b){
for(a = 0; a < lab->color_count; ++a){
//printf("%d\t", combinations[b*lab->color_count + a]);
printf("%d\t", combinations[b*lab->color_count + a]);
}
printf("\n");
}
The problem is when I print the array in the fuction I get the correct values but when printing it in the main random values get printed. As far as I understood I was passing a pointer so the values should be the same. Could someone please explain me what is happening and how to fix this?
Extra information: The method is for calculating the combinations.
EDIT: MVCE
#include <stdio.h>
#include <stdlib.h>
const int times[] = { 0, 1, 2, 3 };
long choose(int * got, int n_chosen, int len, int max_types, int n, int states, int * comb){
int i;
long count = 0;
if (n_chosen == len) {
if (!got) return 1;
for (i = 0; i < len; i++){
comb[len*i + n] = times[got[i]];
printf("%d\n",comb[len*i + n] );
}
return 1;
}
for (i = 0; i < max_types; i++) {
if (got) got[n_chosen] = i;
count += choose(got, n_chosen + 1, len, max_types, n, states, comb);
++n;
}
return count;
}
int main(){
int num_states = 4;
int chosen[4];
int * combinations = malloc(sizeof(int)*num_states*1);
choose(chosen, 0, 1, 4, 0, num_states, combinations);
printf("\n");
int a, b;
for(b=0; b < 1; ++b){
for(a = 0; a < num_states; ++a){
printf("%d\n", combinations[b*2 + a]);
}
}
return 0;
}
I have edited the MVCE with a working code in case anyone ever needs this.

Error when freeing memory [closed]

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 am writing some code to compute the sum of fibonacci values up to n, as stored in an array. For only certain values of n, I get an error on calling free().
Edit: This code should now compile.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
long fib(long *fibs, int n);
int main(int argc, char *argv[]) {
long num, sum;
long n;
long *fibs;
if(argc < 2) {
printf("Usage %s n\n", argv[0]);
exit(EXIT_SUCCESS);
}
n = strtol(argv[1], NULL, 10);
printf("%ld\n", n);
printf("--Allocating memory\n");
fibs = (long *) malloc(sizeof(long) * n);
printf("--Memory allocated\n");
fibs[0] = 1;
fibs[1] = 1;
sum = 0;
for(int i = 0; i <= n; i++) {
num = fib(fibs, i);
sum += num;
printf("%ld\n", num);
}
printf("%ld\n", sum);
printf("--Freeing memory\n");
free(fibs);
printf("--Memory freed\n");
}
long fib(long *fibs, int n) {
if((n == 0) || (n == 1)) {
return 1;
}
fibs[n] = fibs[n - 1] + fibs[n - 2];
return fibs[n];
}
For instance, when I call the program ./fibsum with n=5, I get a core dump.
The lines
fibs[n] = 1;
and
fibs[n] = fibs[n - 1] + fibs[n - 2];
modify memory beyond the legal range. The legal range is fibs[0] - fibs[n-1]. Due to that, the program displays undefined behavior. In your case, the undefined behavior manifests in the form of problem in the call to free.
You may want to allocate one more element than you are currently allocating. Instead of
fibs = (long *) malloc(n * sizeof(n));
use
fibs = malloc((n+1) * sizeof(n));
See an SO post on why you should not cast the return value of malloc.
Like i told you in the comments, you are overflowing when using <= instead of < in the loop. Take a look at the following example, this is by no means trying to be a "cleaned up" version of your code, I just made it work without changing too much.
#include <stdio.h>
#include <stdlib.h>
int number = 300;
long* fib(long* fibs, int n)
{
if (n == 0 || n == 1)
{
fibs[n] = 1;
}
else
{
fibs[n] = (fibs[n-1] + fibs[n-2]);
}
return fibs;
}
int main(int argc, char *argv[])
{
long* fibs = (long*)malloc(number * sizeof(long));
long sum = 0;
for (int i = 0; i < number; ++i) //changed <= to < like i said in the comments
{
sum += fib(fibs, i)[i];
printf("%d\n", sum);
}
printf("\n\nSum of everything: %ld\n", sum);
free(fibs); //no problem
return 0;
}
There are number of problems -
i is undeclared in main.
n is not declared in main.
And most important one this loop-
for(i = 0; i <= n; i++)
As you allocate memory for n items but loop goes from 0 to n .You forgot it should be till n-1 .Thus behaviour is undefined.
As case you described (n=5 so loop should be from 0 to 4).
There are few problems in your code, some are typing mistake I guess, some are logical problem:
You forgot to type n and i
Never cast malloc, so instead of fibs = (long *) malloc(n * sizeof(n)); try fibs = malloc(n * sizeof(long));
In the for loop, instead of for(i = 0; i <= n; i++) use for(i = 0; i < n; i++)
sum += fib(fibs, i); here, sum is long but fib() returns long *, so change function defalcation long *fib(long *fibs, int n) to long fib(long *fibs, int n)
I update your code then run and get output : 12.
The modified code:
#include <stdio.h>
#include <stdlib.h>
long fib(long *fibs, int n) {
if((n == 0) || (n == 1)) {
fibs[n] = 1;
} else {
fibs[n] = fibs[n - 1] + fibs[n - 2];
}
return fibs[n];
}
int main(int argc, char *argv[]) {
long *fibs;
long sum = 0;
int n = 6, i;
fibs = malloc(n * sizeof(long));
long tem;
for(i = 0; i < n; i++) {
tem = fib(fibs, i);
sum += tem;
}
printf("%ld\n", sum);
free(fibs);
}

Resources