I'm trying to sort an array of characters in C. My bubble sort algorithm is a standard one but when I try to print the arrays after using the sort method they appear to be empty.
Is this a problem with my pointer usage?
#include <stdio.h>
#include <string.h>
char Gstr1[256];
char Gstr2[256];
void load();
void printArrays();
void sortArray(char *array);
main()
{
load();
printArrays();
sortArray(&Gstr1[0]);
sortArray(&Gstr2[0]);
printf("\n\n");
printArrays();
}
void load()
{
memcpy (Gstr1,"Sed aliquam neque fermentum leo semper sagittis. Curabitur imperdiet, libero vulputate laoreet tristique, magna justo posuere, quis rutrum ligula tortor vitae eros. Phasellus sed dignissim elit, nec dictum ligula. Vivamus ornare ultrices odio eget dictum.",255);
memcpy (Gstr2,"Lorem ipsum dolor si amet, consectetur adipiscing elit. Aenean dapibus libero a convallis sodales. Mauris placerat nisl leo, vitae tincidunt turpis tristique in. Pellentesque vehicula nisl vitae efficitur ornare. Nunc imperdiet sem, in aliquam rhoncus at.",255);
}
void printArrays()
{
printf(Gstr1);
printf("\n\n");
printf(Gstr2);
}
void sortArray(char *array)
{
int i,j;
char temp;
for(i=0;i<(256-1);i++)
for(j=0;j<(256-i-1);j++)
{
if((int)*(array+j)>(int)*(array+(j+1)))
{
temp=*(array+j);
*(array+j)=*(array+(j+1));
*(array+(j+1))=temp;
}
}
}
This is because of the string length. The length of first string is 256 and second is 257, and you're not taking care of '\0' character. Hence, it is advisable to use memcpy_s() instead of memcpy() and also, use strlen() instead of hardcoding the array size in the for loops. However, with minor correction of the for loop limit, the following code produces the output.
Code:
#include <stdio.h>
#include <string.h>
char Gstr1[256];
char Gstr2[256];
void load();
void printArrays();
void sortArray(char *array);
main()
{
load();
printArrays();
sortArray(&Gstr1[0]);
sortArray(&Gstr2[0]);
printf("\n\n");
printArrays();
}
void load()
{
memcpy (Gstr1,"Sed aliquam neque fermentum leo semper sagittis. Curabitur imperdiet, libero vulputate laoreet tristique, magna justo posuere, quis rutrum ligula tortor vitae eros. Phasellus sed dignissim elit, nec dictum ligula. Vivamus ornare ultrices odio eget dictum.",255);
memcpy (Gstr2,"Lorem ipsum dolor si amet, consectetur adipiscing elit. Aenean dapibus libero a convallis sodales. Mauris placerat nisl leo, vitae tincidunt turpis tristique in. Pellentesque vehicula nisl vitae efficitur ornare. Nunc imperdiet sem, in aliquam rhoncus at.",255);
}
void printArrays()
{
printf(Gstr1);
printf("\n\n");
printf(Gstr2);
}
void sortArray(char *array)
{
int i,j;
char temp;
for(i=0;i<strlen(array);i++)
for(j=0;j<(strlen(array)-i-1);j++)
{
if((int)*(array+j)>(int)*(array+(j+1)))
{
temp=*(array+j);
*(array+j)=*(array+(j+1));
*(array+(j+1))=temp;
}
}
}
You sort the last character in the array as well resulting in a sorted character array with leading null terminator.
Therefore just adjust your loops to fix your issue as shown below.
Of course it would be better to pass the array size with a parameter but that's a different topic :)
void sortArray(char *array)
{
int i,j;
char temp;
for(i=0;i<(256-2);i++)
for(j=0;j<(256-i-2);j++)
{
if((int)*(array+j)>(int)*(array+(j+1)))
{
temp=*(array+j);
*(array+j)=*(array+(j+1));
*(array+(j+1))=temp;
}
}
}
Related
Working on a CS class - C course problem. Part of the problem is to create a function to print the specified length from a char buffer, given a char pointer to print from.
Signature of the function to be called in loop:
bool printLine(char cbuffer, char *ptr, int bufferFillLength)
where cbuffer is the pointer to the beginning of the buffer, ptr is the pointer to the start of the string to print. Variable bufferFillLength is the number of characters to print from the buffer starting at ptr.
The function should be called in loop until the end of the line is reached (i.e function returns false).
Here is my attempt but not working and looking for help.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define BUFFER_SIZE 300
bool printLine (char cbuffer, char *ptr, int printLength){
char *bufferprinttext;
strncpy (bufferprinttext, &cbuffer[ptr], printLength);
printf("%s", bufferprinttext);
if(bufferprinttext[strlen(bufferprinttext)-1] == '\n') {
//end of line reasched - return false;
return false;
}
return true;
}
int main(int argc, char *argv[])
{
char cbuffer[BUFFER_SIZE];
int printLength = 25;
bool isItEndOfBuffer = false;
int bufferCounter = 0;
cbuffer = "Fusce dignissim facilisis ligula consectetur hendrerit. Vestibulum porttitor aliquam luctus. Nam pharetra lorem vel ornare condimentum. Praesent et nunc at libero vulputate convallis. Cras egestas nunc vitae eros vehicula hendrerit. Pellentesque in est et sapien dignissim molestie.";
while(isItEndOfBuffer == false) {
++bufferCounter;
isItEndOfBuffer = printLine(cbuffer, &cbuffer[printLength * bufferCounter], printLength);
}
}
cbuffer is not a pointer as you say but is passed by value, thus you are not holding it's original reference as you seem to want. Try with the signature
bool printLine (char *cbuffer, char *ptr, int printLength);
Jonathan Leffler: I have update the code per your comment. The function prints now but truncated at the beginning. Couldn't figure out what I am missing.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define BUFFER_SIZE 300
bool printLine (char cbuffer, char *ptr, int printLength){
for (int i = 0; i < printLength; i++) {
putchar(*ptr++);
if(*ptr == '\0') {
//end of line reasched - return false;
return true;
}
}
return false;
}
int main(int argc, char *argv[])
{
int printLength = 25;
bool isItEndOfBuffer = false;
int bufferCounter = 0;
char* cbuffer = "Fusce dignissim facilisis ligula consectetur hendrerit. Vestibulum porttitor aliquam luctus. Nam pharetra lorem vel ornare condimentum. Praesent et nunc at libero vulputate convallis. Cras egestas nunc vitae eros vehicula hendrerit. Pellentesque in est et sapien dignissim molestie.";
//printf ("cbuffer - start ptr=%p \n", &cbuffer[0]);
printf("Text to print:\n %s \n\n", cbuffer);
printf("But text is truncated at the begining by printLength(i.e. 25): \n");
//printf ("\nisItEndOfBuffer=%d \n", isItEndOfBuffer );
while( !isItEndOfBuffer ) {
++bufferCounter;
//printf ("ptr=%p \n", &cbuffer[printLength * bufferCounter]);
isItEndOfBuffer = printLine(*cbuffer, &cbuffer[printLength * bufferCounter], printLength);
//printf ("\nisItEndOfBuffer=%d \n", isItEndOfBuffer );
}
}
Output:
Text to print:
Fusce dignissim facilisis ligula consectetur hendrerit. Vestibulum porttitor aliquam luctus. Nam pharetra lorem vel ornare condimentum. Praesent et nunc at libero vulputate convallis. Cras egestas nunc vitae eros vehicula hendrerit. Pellentesque in est et sapien dignissim molestie.
But text is truncated at the begining by printLength(i.e. 25):
ligula consectetur hendrerit. Vestibulum porttitor aliquam luctus. Nam pharetra lorem vel ornare condimentum. Praesent et nunc at libero vulputate convallis. Cras egestas nunc vitae eros vehicula hendrerit. Pellentesque in est et sapien dignissim molestie.
I'm trying to insert data into my firebase JSon, which has the following structure
{
"gerechten" : [ {
"id" : "1",
"name" : "spaghetti",
"description" : "Spaghetti bolognese met veel liefde gemaakt op grootmoeders wijze.",
"kind" : "Pasta",
"preparation" : "1)Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?",
"img" : "../../assets/img/gerechten/spaghetti.jpg",
"ingredients" : [ "5kg wortelen", "3 aardappelen", "1 komkommer", "2 eieren", "3 eetlepels bloem", "50g zout" ]
} ]
}
as you see, i got an array 'gerechten" and inside each array another array "ingredients". Right now i can add a items but i have no idea how to fill my "ingredients".
Is there a way to let the user give inputs and with each ',' there is a new ingredient? Eq;
5 eggs, 2 appels, 1 spoon of suger
sould create
"ingredients" : ["5 eggs", "2 appels", "1 spoon of suger"]
Also, as of now I have to insert my id manually, how can I make it so it takes automatic the next ID? when I leave the ID empty I got this result:
Firebase arror
Its does not put it inside an array
this is how i do it at the moment:
create.ts:
gerecht = {
description: "",
kind: "",
name: "",
prepartion: "",
ingredients: "",
id: "",
img: ""
}
create() {
this.db.create(this.gerecht.id, this.gerecht.description, this.gerecht.kind, this.gerecht.name, this.gerecht.prepartion, this.gerecht.img, this.gerecht.ingredients)
this.navCtrl.push(HomePage)
}
firedataservice:
create(id: string, description: string, kind: string, name: string, preparation: string, img: string, ingredients: string) {
this.db.object('gerechten/'+id).update({
id: id,
description: description,
kind: kind,
name: name,
preparation: preparation,
img: img,
ingredients: ingredients
})
}
As a student with a background in Java, C#, a bit of Python and web-based languages, I am currently learning C. For practice I am coding a GTK application to convert a longer text to smaller pieces of text of 140 characters max. This use case is meant to post longer texts on Twitter easily.
So I experimented a bit and the application is working more or less at this moment. However, it regularly shows unexpected behaviour. When inserting text in the GTK interface (TextView) and clicking a button calling the below method, the output put back into the TextView sometimes looks like this:
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut eni
(1/4)
m ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in rep
(2/4)
(0/1981836649)
rehenderit in voluptate velit esse cillum dolore
eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in (3/4)
(0/1763734633)
(1701998412/544044403)
culpa qui officia deserunt mollit anim id est laborum. (4/4)
Or similar when inserting Lorem Ipsum as input. Sometimes it also cuts an entire part (e.g., only the (4/4) part is printed). The expected output is:
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut eni (1/4)
m ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip > ex ea commodo consequat. Duis aute irure dolor in rep (2/4)
rehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in (3/4)
culpa qui officia deserunt mollit anim id est laborum. (4/4)
It applies to the following method, which is hooked to a GTK button:
void on_do_tweet_clicked()
{
char *text = get_text_from_text_view(g_tv_tweet_text);
int text_length = strlen(text);
int tweet_no = text_length / 130 + (text_length % 130 != 0);
char tweets[(int) tweet_no][140 * sizeof(char*)];
for (int i = 0; i < tweet_no; i++)
{
char *tweet = (char*) malloc(sizeof(char*) * 140);
if (tweet_no != 1) {
if (i + 1 == tweet_no) {
strcpy(tweet, &text[i * 130]);
} else {
strncpy(tweet, &text[i * 130], 130);
}
strcat(tweet, " (%d/%i)\n\0");
sprintf(tweets[i], tweet, i + 1, tweet_no);
} else {
strcpy(tweet, &text[i * 130]);
sprintf(tweets[i], tweet);
}
free(tweet);
}
free(text);
GtkTextBuffer *buffer = gtk_text_view_get_buffer((GtkTextView *) g_tv_tweet_text);
gtk_text_buffer_set_text(buffer, "", 0);
for (int i = 0; i < sizeof(tweets) / sizeof(tweets[0]); i++)
{
gtk_text_buffer_insert_at_cursor(buffer, tweets[i], strlen(tweets[i]));
}
memset(tweets, 0, sizeof(tweets));
}
I did some research on the problem and I suspect it has to do with either an problem with encodings or a problem related to pointers. However, my searches on the web did not result in a solution and my knowledge of C is still too limited to draw my own conclusions.
So here's the question: could anyone explain why this method is showing this behaviour and give me a hint on how to solve it?
Thank you in advance!
Thanks to #AnT I got it working. The final code is:
void on_do_tweet_clicked()
{
char *text = get_text_from_text_view(g_tv_tweet_text);
int text_length = strlen(text);
int tweet_no = text_length / 130 + (text_length % 130 != 0);
char tweets[(int) tweet_no][140 * sizeof(char)];
for (int i = 0; i < tweet_no; i++)
{
char *tweet = (char*) malloc(sizeof(char) * 140);
if (tweet_no != 1) {
if (i + 1 == tweet_no) {
strcpy(tweet, &text[i * 130]);
} else {
strncpy(tweet, &text[i * 130], 130);
}
tweet[130] = '\0';
strcat(tweet, " (%d/%i)\n");
sprintf(tweets[i], tweet, i + 1, tweet_no);
} else {
strcpy(tweets[i], &text[i * 130]);
}
free(tweet);
}
free(text);
GtkTextBuffer *buffer = gtk_text_view_get_buffer((GtkTextView *) g_tv_tweet_text);
gtk_text_buffer_set_text(buffer, "", 0);
for (int i = 0; i < sizeof(tweets) / sizeof(tweets[0]); i++)
{
gtk_text_buffer_insert_at_cursor(buffer, tweets[i], strlen(tweets[i]));
}
memset(tweets, 0, sizeof(tweets));
}
Instead of returning an array of objects, pulling from a JSON file, it returns an array of 4 arrays containing 4 objects? Why? JSON file name is portfolios.json.
'use strict';
var portfolioArray = [];
function Portfolio (portfoliosDataObj) {
this.title = portfoliosDataObj.title;
this.body = portfoliosDataObj.body;
this.img = portfoliosDataObj.img;
}
Portfolio.prototype.toHtml = function() {
var renderPortfolios = Handlebars.compile($('#portfolio-template').text());
return renderPortfolios(this);
console.log(this);
};
$.getJSON('/data/portfolios.json', function(portfolios) {
portfolios.forEach(function(portfoliosDataObject) {
var portfolio = new Portfolio(portfoliosDataObject);
portfolioArray.push(portfolios);
console.log(portfolios);
});
});
function print () {
portfolioArray.forEach(function(data) {
$('#portfolioSection').append(data.toHtml());
});
}
Portfolio();
print();
JSON FILE - Adding for reference.
[{
"title": "CodeFellows/Code201",
"body": "content1",
"img": ""
},
{
"title": "CodeFellows/Code301",
"body": "lorem ipsum"
},
{
"title": "Upcoming Projects/Other interest",
"body": "lorem impsum",
"img": "/images/blog.jpg"
},
{
"title": "Illustrations",
"body": "lorem ipsum",
"img": "/images/portfolio.png"
}]
IGNORE need more content that isn't code to post....
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam porttitor leo at tellus facilisis, id suscipit ipsum suscipit. Aenean venenatis, quam semper efficitur hendrerit, odio diam condimentum odio, id sagittis lorem tellus vel mauris. Cras enim neque, malesuada sit amet lacinia et, ullamcorper non sapien. Integer id hendrerit nulla, vitae tristique tortor. Aenean in arcu eget massa pulvinar dictum. Aliquam dictum fermentum sapien id iaculis. Ut malesuada varius lacinia. Maecenas scelerisque facilisis mattis.
The file returns an array of 4 objects, and not arrays.
{
"title": "CodeFellows/Code201",
"body": "content1",
"img": ""
}
is a javascript object, not an array (notice the curly braces {}).
The outer one is an array. (notice the square brackets[]).
You can get to the objects by doing a console.log(portfolios[0]);
The issue is with this code. You are pushing portfolios in portfolioArray instead of portfolio. Also you were doing console.log for portfolios which is why it was showing 4 arrays. I have fixed the code. Let me know if it works for you.
$.getJSON('/data/portfolios.json', function(portfolios) {
portfolios.forEach(function(portfoliosDataObject) {
var portfolio = new Portfolio(portfoliosDataObject);
portfolioArray.push(portfolio);
console.log(portfolio);
});
});
I am attempting to append a JSON element to an already existing array in my database. I know about jsonb_set however I can't upgrade to Postgres 9.4 as this is a groovy project and the latest postgresql version on Maven is 9.4.
I currently have a json structure like this:
"playersContainer": {
"players": [
{
"id": "1",
"name": "Nick Pocock",
"teamName": "Shire Soldiers",
"bio" : "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla imperdiet lorem tellus, in bibendum sem dignissim sed. Etiam eu elit sit amet lacus accumsan blandit sed ut dolor. Mauris vel dui non nisi vestibulum commodo vel id magna. Donec egestas magna in tincidunt mollis. Fusce mauris arcu, rhoncus ut lacus sed, fermentum ultrices elit. In sollicitudin at ex dapibus vestibulum. Pellentesque congue, est id lobortis viverra, mauris lectus pharetra orci, ut suscipit nisl purus vehicula est. Aliquam suscipit non velit vel feugiat. Quisque nec dictum augue.",
"ratings": [
1,
5,
6,
9
],
"assists": 17,
"manOfTheMatches": 20,
"cleanSheets": 1,
"data": [
3,
2,
3,
5,
6
],
"totalGoals": 19
}
}
I want to append new players to the player array and update my database, I tried doing an update but it wiped the rest of the data. Is there a way to target the players array and append the new json object to it?
Unfortunately 9.4 does not have json_set function. You can use something like this:
WITH old_players AS (
SELECT $1 AS j
), new_player AS (
SELECT $2 AS j
), all_players AS (
SELECT json_array_elements(j->'playersContainer'->'players') AS p
FROM old_players
UNION ALL
SELECT *
FROM new_player
) SELECT ('{"playersContainer": {"players": ' || json_agg(p) || '}}')::json
FROM all_players
;
You can use it as function:
CREATE OR REPLACE FUNCTION add_player(old_player json, new_player json) RETURNS json AS $$
WITH all_players AS (
SELECT json_array_elements(($1)->'playersContainer'->'players') AS p
UNION ALL
SELECT $2
)
SELECT ('{"playersContainer": {"players": ' || json_agg(p) || '}}')::json
FROM all_players
$$ LANGUAGE sql IMMUTABLE;
And after that you can just call it :
UPDATE site_content SET content = add_player(content, '{"id": "2", "name": "Someone Else"}') where id = :id;