Funny behavior from sscanf - c

I have a piece of code below which basically reads a text file data.txt and prints to the console. The content of data.txt is below the code listing;
#include "stdio.h"
#define BUFFER_SIZE 93
int main(int argc, char *argv[]){
const char *datafile;
char line[BUFFER_SIZE],*string1;
int a,b,c,d,e;
FILE * File_ptr;
datafile = "data.txt";
File_ptr = fopen(datafile,"r");
if(File_ptr == NULL ){
printf("Error opening file %s\n",datafile);
}
while(fgets(line,BUFFER_SIZE,File_ptr) != 0){
puts(line);
sscanf(line, "%d %d %d %d %d %s", &a,&b,&c,&d,&e,string1);
printf("%d, %d, %d, %d, %d, %s\n",a,b,c,d,e,string1);
}
fclose(File_ptr);
}
Content in data.txt:
100 200 888 456 5443 file1.abc
180 670 812 496 5993 file2.abc
160 230 345 546 5123 file3.abc
23 455 342 235 214 file4.abc
233 5455 3142 2435 1214 file5.abc
What I don't understand is: if the BUFFER_SIZE is defined as < 97, the output would be like this:
100 200 888 456 5443 file1.abc
100 200 888 456 5443 (null)
180 670 812 496 5993 file2.abc
180 670 812 496 5993 (null)
160 230 345 546 5123 file3.abc
160 230 345 546 5123 (null)
23 455 342 235 214 file4.abc
23 455 342 235 214 (null)
233 5455 3142 2435 1214 file5.abc
233 5455 3142 2435 1214 (null)
If the BUFFER_SIZE is defined as 97 ~ 120, the output would be OK, like this:
100 200 888 456 5443 file1.abc
100 200 888 456 5443 file1.abc
180 670 812 496 5993 file2.abc
180 670 812 496 5993 file2.abc
160 230 345 546 5123 file3.abc
160 230 345 546 5123 file3.abc
23 455 342 235 214 file4.abc
23 455 342 235 214 file4.abc
233 5455 3142 2435 1214 file5.abc
233 5455 3142 2435 1214 file5.abc
If the BUFFER_SIZE is defined as >120, a segmentation fault will be triggered at the sscanf() call.
Can someone enlighten me of the reason for this behavior?

Your string1 is an uninitialized pointer that points nowhere. Your sscanf attempts to store data into the location pointed by string1, which is nowhere. Your program exhibits undefined behavior. It can segfault, it can output nonsense, it can do anything. The actual behavior of such program can change for no explainable reasons. This is exactly what you observe.

Related

What is the behavior of iscntrl?

The function iscntrl is standardized. Unfortuneately on C99 we have:
The iscntrl function tests for any control character
Considering the prototype which is int iscntrl(int c); I am expecting something like true for 0..31 and perhaps 127 too. However in the following:
#include <stdio.h>
#include <ctype.h>
int main()
{
int i;
printf("The ASCII value of all control characters are ");
for (i=0; i<=1024; ++i)
{
if (iscntrl(i)!=0)
printf("%d ", i);
}
return 0;
}
I get this output:
The ASCII value of all control characters are 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 127 264 288 308 310 320 334
336 346 348 372 374 390 398 404 406 412 420 428 436 444 452 458 460 466 468 474
476 484 492 500 506 512 518 530 536 542 638 644 656 662 668 682 688 694 700 706
708 714 716 718 760 774 780 782 788 798 826 834 836 846 854 856 864 866 874 876
882 888 890 892 898 900 908 962 968 970 988 994 1000
So I am wondering how this function is implemented behind the scene. I tried to search on the standard library, but the answer is not obvious.
https://github.com/bminor/glibc/search?q=iscntrl&unscoped_q=iscntrl
Any ideas?
You are invoking undefined behavior by passing improper values to iscntrl().
Per 7.4 Character handling <ctype.h>, paragraph 1:
The header <ctype.h> declares several functions useful for classifying and mapping characters. In all cases the argument is an int, the value of which shall be representable as an unsigned char or shall equal the value of the macro EOF. If the argument has any other value, the behavior is undefined.

Modifying function that malloc's a 2d array to a 3d array in C

I'm very new to C, this is the first program I'm writing in it. My professor gave us a function for allocating memory for a 2d array, called malloc2d. I am supposed to modify it to allocate memory for a 3d array, but being so new to C I am not sure how to go about it. I've tried looking at other malloc functions for 3d arrays but none of them look similar to the one I was given. Similarly, we have a free2d function that also needs to be modified for a 3d array. Here are the functions to be modified:
void** malloc2D(size_t rows, size_t cols, size_t sizeOfType){
void* block = malloc(sizeOfType * rows * cols);
void** matrix = malloc(sizeof(void*) * rows);
for (int row = 0; row < rows; ++row) {
matrix[row] = block + cols * row * sizeOfType;
}//for
return matrix;
}//malloc2D
void free2D(void*** matrix){
free((*matrix)[0]);
free((*matrix));
matrix = NULL;
}//free2D
Any help or a start would be greatly appreciated.
I find it difficult to believe this is a first exercise; it is moderately tricky, at least.
Fix the 2D code
The first step should be to clean up the malloc2D() function so it doesn't casually use a GCC extension — indexing a void * — because Standard C does not allow that (because sizeof(void) is undefined in Standard C; GNU C defines it as 1). Also, the bug in free2D() needs to be fixed; the last line of the function should read *matrix = NULL; (the * was omitted). That code should be tested too, because the correct way to access the matrix is not obvious.
Here's some modified code (variables renamed for consistency with the 3D version) that tests the revised 2D code:
/* SO 4885-6272 */
#include <stdlib.h>
#include <stdio.h>
#include <inttypes.h>
/* Should be declared in a header for use in other files */
extern void **malloc2D(size_t rows, size_t cols, size_t sizeOfType);
extern void free2D(void ***matrix);
void **malloc2D(size_t rows, size_t cols, size_t sizeOfType)
{
void *level2 = malloc(sizeOfType * rows * cols);
void **level1 = malloc(sizeof(void *) * rows);
if (level2 == NULL || level1 == NULL)
{
free(level2);
free(level1);
return NULL;
}
for (size_t row = 0; row < rows; ++row)
{
level1[row] = (char *)level2 + cols * row * sizeOfType;
}
return level1;
}
void free2D(void ***matrix)
{
free((*matrix)[0]);
free((*matrix));
*matrix = NULL;
}
static void test2D(size_t m2_rows, size_t m2_cols)
{
printf("rows = %zu; cols = %zu\n", m2_rows, m2_cols);
void **m2 = malloc2D(m2_rows, m2_cols, sizeof(double));
if (m2 == NULL)
{
fprintf(stderr, "Memory allocation failed for 2D array of size %zux%zu doubles\n",
m2_rows, m2_cols);
return;
}
printf("m2 = 0x%.12" PRIXPTR "; m2[0] = 0x%.12" PRIXPTR "\n",
(uintptr_t)m2, (uintptr_t)m2[0]);
for (size_t i = 0; i < m2_rows; i++)
{
for (size_t j = 0; j < m2_cols; j++)
((double *)m2[i])[j] = (i + 1) * 10 + (j + 1);
}
for (size_t i = 0; i < m2_rows; i++)
{
for (size_t j = 0; j < m2_cols; j++)
printf("%4.0f", ((double *)m2[i])[j]);
putchar('\n');
}
free2D(&m2);
printf("m2 = 0x%.16" PRIXPTR "\n", (uintptr_t)m2);
}
int main(void)
{
test2D(4, 5);
test2D(10, 3);
test2D(3, 10);
//test2D(300000000, 1000000000); /* 2132 PiB - should fail to allocate on sane systems! */
return 0;
}
When run on a MacBook Pro running macOS High Sierra 10.13.3, compiling with GCC 7.3.0, I get the output:
rows = 4; cols = 5
m2 = 0x7F83C04027F0; m2[0] = 0x7F83C0402750
11 12 13 14 15
21 22 23 24 25
31 32 33 34 35
41 42 43 44 45
m2 = 0x0000000000000000
rows = 10; cols = 3
m2 = 0x7F83C0402750; m2[0] = 0x7F83C04028C0
11 12 13
21 22 23
31 32 33
41 42 43
51 52 53
61 62 63
71 72 73
81 82 83
91 92 93
101 102 103
m2 = 0x0000000000000000
rows = 3; cols = 10
m2 = 0x7F83C04027A0; m2[0] = 0x7F83C04028C0
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
m2 = 0x0000000000000000
With the monster allocation included, the trace ended:
alloc3d19(8985,0x7fffa5d79340) malloc: *** mach_vm_map(size=2400000000000000000) failed (error code=3)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
Memory allocation failed for 2D array of size 300000000x1000000000 doubles
Adapt to 3D code
I chose to call the leading dimension of the 3D array a 'plane'; each plane contains a 2D array with r rows by c columns.
For me, I drew myself a diagram to convince myself I was getting the assignments correct — after I'd messed up a couple of times. In each cell in the first two tables, the first number is the index number of the cell in the containing array (level1 in the first table) and the second is the index number of the cell in the next level (level2 in the first table). The numbers in the level3 table are simply the indexes into the array of doublea.
level1 (planes: 4)
╔═══════╗
║ 0: 00 ║
║ 1: 05 ║
║ 2: 10 ║
║ 3: 15 ║
╚═══════╝
level2 (planes: 4; rows: 5)
╔════════╦════════╦════════╦════════╦════════╗
║ 00: 00 ║ 01: 06 ║ 02: 12 ║ 03: 18 ║ 04: 24 ║
║ 05: 30 ║ 06: 36 ║ 07: 42 ║ 08: 48 ║ 09: 54 ║
║ … ║ … ║ … ║ … ║ … ║
╚════════╩════════╩════════╩════════╩════════╝
level3 (planes: 4; rows: 5; cols: 6)
╔════╦═════╦═════╦═════╦═════╦═════╗
║ 0 ║ 1 ║ 2 ║ 3 ║ 4 ║ 5 ║
║ 6 ║ 7 ║ 8 ║ 9 ║ 10 ║ 11 ║
║ 12 ║ 13 ║ 14 ║ 15 ║ 16 ║ 17 ║ Plane 0
║ 18 ║ 19 ║ 20 ║ 21 ║ 22 ║ 23 ║
║ 24 ║ 25 ║ 26 ║ 27 ║ 28 ║ 29 ║
╠════╬═════╬═════╬═════╬═════╬═════╣
║ 30 ║ 31 ║ 32 ║ 33 ║ 34 ║ 35 ║
║ 36 ║ 37 ║ 38 ║ 39 ║ 40 ║ 41 ║ Plane 1
║ … ║ … ║ … ║ … ║ … ║ … ║
╚════╩═════╩═════╩═════╩═════╩═════╝
With that diagram in place — or a paper and pen version with arrows scrawled over it, the values in the cell of plane p in level1 is p * rows; the values of in the cell of plane p, row r in level2 is p * rows + r) * cols; the values in the cell of plane p, row r, cell c in level3 is (p * rows + r) * cols + c. But the values are not integers; they're pointers. Consequently, the values have to be scaled by an appropriate size and added to the base address for the level1, level2 or level3 space.
That leads to code like this:
#include <stdlib.h>
#include <stdio.h>
#include <inttypes.h>
/* Should be declared in a header for use in other files */
extern void ***malloc3D(size_t planes, size_t rows, size_t cols, size_t sizeOfType);
extern void free3D(void ****matrix);
void ***malloc3D(size_t planes, size_t rows, size_t cols, size_t sizeOfType)
{
void *level3 = malloc(sizeOfType * planes * rows * cols);
void **level2 = malloc(sizeof(void *) * planes * rows);
void ***level1 = malloc(sizeof(void **) * planes);
//printf("planes = %zu; rows = %zu; cols = %zu; ", planes, rows, cols);
//printf("level1 = 0x%.12" PRIXPTR "; level2 = 0x%.12" PRIXPTR "; level3 = 0x%.12" PRIXPTR "\n",
// (uintptr_t)level1, (uintptr_t)level2, (uintptr_t)level3);
fflush(stdout);
if (level3 == NULL || level2 == NULL || level1 == NULL)
{
free(level3);
free(level2);
free(level1);
return NULL;
}
for (size_t plane = 0; plane < planes; plane++)
{
level1[plane] = (void **)((char *)level2 + plane * rows * sizeof(void **));
//printf("level1[%zu] = 0x%.12" PRIXPTR "\n", plane, (uintptr_t)level1[plane]);
for (size_t row = 0; row < rows; ++row)
{
level2[plane * rows + row] = (char *)level3 + (plane * rows + row) * cols * sizeOfType;
//printf(" level2[%zu] = 0x%.12" PRIXPTR "\n",
// plane * rows + row, (uintptr_t)level2[plane * rows + row]);
}
}
return level1;
}
void free3D(void ****matrix)
{
free((*matrix)[0][0]);
free((*matrix)[0]);
free((*matrix));
*matrix = NULL;
}
static void test3D(size_t m3_plns, size_t m3_rows, size_t m3_cols)
{
printf("planes = %zu; rows = %zu; cols = %zu\n", m3_plns, m3_rows, m3_cols);
void ***m3 = malloc3D(m3_plns, m3_rows, m3_cols, sizeof(double));
if (m3 == NULL)
{
fprintf(stderr, "Memory allocation failed for 3D array of size %zux%zux%zu doubles\n",
m3_plns, m3_rows, m3_cols);
return;
}
printf("m3 = 0x%.12" PRIXPTR "; m3[0] = 0x%.12" PRIXPTR "; m3[0][0] = 0x%.12" PRIXPTR "\n",
(uintptr_t)m3, (uintptr_t)m3[0], (uintptr_t)m3[0][0]);
for (size_t i = 0; i < m3_plns; i++)
{
for (size_t j = 0; j < m3_rows; j++)
{
for (size_t k = 0; k < m3_cols; k++)
((double *)m3[i][j])[k] = (i + 1) * 100 + (j + 1) * 10 + (k + 1);
}
}
for (size_t i = 0; i < m3_plns; i++)
{
printf("Plane %zu:\n", i + 1);
for (size_t j = 0; j < m3_rows; j++)
{
for (size_t k = 0; k < m3_cols; k++)
printf("%4.0f", ((double *)m3[i][j])[k]);
putchar('\n');
}
putchar('\n');
}
free3D(&m3);
printf("m3 = 0x%.16" PRIXPTR "\n", (uintptr_t)m3);
}
int main(void)
{
test3D(4, 5, 6);
test3D(3, 4, 10);
test3D(4, 3, 7);
test3D(4, 9, 7);
test3D(30000, 100000, 100000000); /* 2132 PiB - should fail to allocate on sane systems! */
return 0;
}
Example output (with outsize memory allocation):
planes = 4; rows = 5; cols = 6
m3 = 0x7FFCC94027F0; m3[0] = 0x7FFCC9402750; m3[0][0] = 0x7FFCC9402850
Plane 1:
111 112 113 114 115 116
121 122 123 124 125 126
131 132 133 134 135 136
141 142 143 144 145 146
151 152 153 154 155 156
Plane 2:
211 212 213 214 215 216
221 222 223 224 225 226
231 232 233 234 235 236
241 242 243 244 245 246
251 252 253 254 255 256
Plane 3:
311 312 313 314 315 316
321 322 323 324 325 326
331 332 333 334 335 336
341 342 343 344 345 346
351 352 353 354 355 356
Plane 4:
411 412 413 414 415 416
421 422 423 424 425 426
431 432 433 434 435 436
441 442 443 444 445 446
451 452 453 454 455 456
m3 = 0x0000000000000000
planes = 3; rows = 4; cols = 10
m3 = 0x7FFCC94027F0; m3[0] = 0x7FFCC9402750; m3[0][0] = 0x7FFCC9402840
Plane 1:
111 112 113 114 115 116 117 118 119 120
121 122 123 124 125 126 127 128 129 130
131 132 133 134 135 136 137 138 139 140
141 142 143 144 145 146 147 148 149 150
Plane 2:
211 212 213 214 215 216 217 218 219 220
221 222 223 224 225 226 227 228 229 230
231 232 233 234 235 236 237 238 239 240
241 242 243 244 245 246 247 248 249 250
Plane 3:
311 312 313 314 315 316 317 318 319 320
321 322 323 324 325 326 327 328 329 330
331 332 333 334 335 336 337 338 339 340
341 342 343 344 345 346 347 348 349 350
m3 = 0x0000000000000000
planes = 4; rows = 3; cols = 7
m3 = 0x7FFCC94027F0; m3[0] = 0x7FFCC9402750; m3[0][0] = 0x7FFCC9402840
Plane 1:
111 112 113 114 115 116 117
121 122 123 124 125 126 127
131 132 133 134 135 136 137
Plane 2:
211 212 213 214 215 216 217
221 222 223 224 225 226 227
231 232 233 234 235 236 237
Plane 3:
311 312 313 314 315 316 317
321 322 323 324 325 326 327
331 332 333 334 335 336 337
Plane 4:
411 412 413 414 415 416 417
421 422 423 424 425 426 427
431 432 433 434 435 436 437
m3 = 0x0000000000000000
planes = 4; rows = 9; cols = 7
m3 = 0x7FFCC94027F0; m3[0] = 0x7FFCC9402840; m3[0][0] = 0x7FFCC9802000
Plane 1:
111 112 113 114 115 116 117
121 122 123 124 125 126 127
131 132 133 134 135 136 137
141 142 143 144 145 146 147
151 152 153 154 155 156 157
161 162 163 164 165 166 167
171 172 173 174 175 176 177
181 182 183 184 185 186 187
191 192 193 194 195 196 197
Plane 2:
211 212 213 214 215 216 217
221 222 223 224 225 226 227
231 232 233 234 235 236 237
241 242 243 244 245 246 247
251 252 253 254 255 256 257
261 262 263 264 265 266 267
271 272 273 274 275 276 277
281 282 283 284 285 286 287
291 292 293 294 295 296 297
Plane 3:
311 312 313 314 315 316 317
321 322 323 324 325 326 327
331 332 333 334 335 336 337
341 342 343 344 345 346 347
351 352 353 354 355 356 357
361 362 363 364 365 366 367
371 372 373 374 375 376 377
381 382 383 384 385 386 387
391 392 393 394 395 396 397
Plane 4:
411 412 413 414 415 416 417
421 422 423 424 425 426 427
431 432 433 434 435 436 437
441 442 443 444 445 446 447
451 452 453 454 455 456 457
461 462 463 464 465 466 467
471 472 473 474 475 476 477
481 482 483 484 485 486 487
491 492 493 494 495 496 497
m3 = 0x0000000000000000
planes = 30000; rows = 100000; cols = 100000000
alloc3d79(9018,0x7fffa5d79340) malloc: *** mach_vm_map(size=2400000000000000000) failed (error code=3)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
Memory allocation failed for 3D array of size 30000x100000x100000000 doubles

My program returns the wrong values

I am making a program that will calculate the minimum and maximum cost of flight (supposed to be a simple program to practice for an exam) using a separate function to calculate the cost of the flight.
the code is this:
#include<stdio.h>
#include<limits.h>
float cost(float k, int ck, int n)
{
int x;
x = (k*ck)/n;
return x;
}
main()
{
int cont=1, n, nv, costmax = 0, costmin = INT_MAX, ck;
float k;
printf("Introduce the number of flights: \n");
scanf("%d", &nv);
for(cont=1; cont <= nv; cont++)
{
printf("Introduce the number of passangers on flight %d:\n", cont);
scanf("%d", &n);
printf("Introduce the number of distance on flight %d:\n", cont);
scanf("%d", &k);
if(k < 500)
{
ck=50;
}
if(k > 500)
{
ck=80;
}
cost(k,ck,n);
if(cost(k, ck, n) < costmin)
{
costmin = cost(k, ck, n);
}
if(cost(k, ck, n) > costmax)
{
costmax = cost(k, ck, n);
}
}
printf("\nMinimum cost = %d \n", costmin);
printf("\nMaximum cost = %d \n", costmax);
}
and we're supposed to use a text file to input the data
156 397 798 375 489 901 937 519 797 205 883 247 1186 738 860 967 550 887 743 753 906 582 819 665 1112 231 1009 761 921 634 686 591 1027 646 1161 424 668 413 1190 423 840 381 431 559 455 496 1105 489 848 775 456 637 664 760 412 689 639 752 669 312 940 955 706 726 579 556 655 335 902 755 665 431 1093 627 569 310 647 327 943 354 647 733 979 711 504 443 509 266 833 856 667 603 1101 670 688 898 498 669 1149 601 808 934 718 880 1053 977 556 719 1012 286 665 882 456 623 437 632 475 320 494 672 775 548 678 935 984 464 1188 641 749 816 1191 528 1092 203 770 923 1153 220 929 321 789 350 720 745 694 790 687 669 826 372 1029 392 839 932 462 806 882 539 524 797 1084 516 449 218 1048 638 751 889 448 479 465 633 1123 862 904 383 494 472 1117 365 415 889 765 670 941 341 929 876 575 940 565 967 850 473 1119 632 953 904 815 316 409 364 959 287 848 584 574 998 915 826 558 877 858 376 817 591 1068 443 447 428 1081 823 1122 373 852 598 995 735 1028 313 623 820 981 505 753 529 574 433 699 875 1032 833 1068 765 949 691 1145 358 505 251 617 417 945 694 889 323 1028 986 567 269 605 337 1153 926 590 607 803 202 1101 232 771 855 759 776 1011 878 884 393 636 230 1098 788 1140 447 1076 537 1077 734 724 266 635 232 406 752 628 743 848 537 490 598 913 416 855 640 634 209 1172 329 705 249 881 882 817
The program doesn't present any errors or warnings when compiling, but when I run it, it says that the minimum cost and the maximum cost are 0...
I've been checking everything over and over and can't find what's wrong.
Any ideas?
BTW, I'm using a linux machine to run the program, don't know if it makes a difference...
Compile with the -Wall flag, this will help you to catch errors by yourself.
Using gcc:
% gcc t.c -Wall
t.c:9:1: warning: return type defaults to ‘int’ [-Wreturn-type]
main()
^
t.c: In function ‘main’:
t.c:20:9: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘float *’ [-Wformat=]
scanf("%d", &k);
^
t.c:41:1: warning: control reaches end of non-void function [-Wreturn-type]
}
^
Using clang:
% clang t.c -Wall
t.c:9:1: warning: type specifier missing, defaults to 'int' [-Wimplicit-int]
main()
^~~~
t.c:20:21: warning: format specifies type 'int *' but the argument has type 'float *' [-Wformat]
scanf("%d", &k);
~~ ^~
%f
2 warnings generated.
Clang suggests you to replace:
scanf("%d", &k);
to
scanf("%f", &k);
And even if it's not as critical, you forgot to define the return type of the main function. Both compilers have replaced it to int but you should also return something at the end of your program.
Finally, as suggested in the comments, you can also use -Wextra. I would also recommend you, while the projects are small enough and that you are still learning, to respect the "0 warning" policy. That will help you to prevent bugs.
Since k is a float, this is wrong:
scanf("%d", &k);
You need:
if (scanf("%f", &k) != 1)
break;
This uses the correct format and checks for errors. A basic debugging technique is to print out the values you've just read to ensure that the program got what you think it should have gotten.
There are other problems too. This code is redundant:
cost(k,ck,n);
if(cost(k, ck, n) < costmin)
{
costmin = cost(k, ck, n);
}
if(cost(k, ck, n) > costmax)
{
costmax = cost(k, ck, n);
}
You call the function up to 5 times to get the same answer each time. The first call you ignore altogether. You should probably use something like:
float new_cost = cost(k,ck,n);
if (new_cost < costmin)
costmin = new_cost;
if (new_cost > costmax)
costmax = cost_max;
You should also use an explicit return type for main():
int main(void)
Normally, 'passengers' is spelled with one 'a' and two 'e's.
It isn't entirely clear whether the cost() function is written appropriately. It takes one float and two int values and combines them and assigns the result to an int before returning that as a float. As written, it will work. Whether that's what you want is another matter. Since costmin and costmax are of type int, there's another level of uncertainty about what's the best type for these values.
Also, generally avoid trailing blanks in your output. A space before \n is almost always … well, if not wrong, superfluous. I'd go for almost always wrong, though. (But it is good that you end messages with a newline — that's a worse problem than trailing blanks, but prevalent in the world of C on Windows.)
Firstly, I see no reading from file. All your readings are from console (stdin).
Also, you are calling the cost function too many times, and sometimes you take no benefit from it, like here:
}
cost(k,ck,n); //<--
if(cost(k, ck, n) < costmin)
I suggest you replace indicated call with:
float c = cost(k, ck, n);
and then use c for checking/assingments instead of calling cost() all over again.
Also, you are assigning a float value to an int in multiple places:
costmax = cost(k, ck, n);
costmin = cost(k, ck, n);
In some places, you use "%d" in scanf and printf for reading/printing a float. You should use "%f".

Recursive QuickSort in C [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I am confused why my recursive quicksort function isn't working.
Here is the original function call:
qSort(quickArr,0,inCount-1,&qSwapCount);
where inCount-1 is the position of the final array element
Here is the recursive quicksort function:
void qSort(int *qArr, int left, int right, int *qCount)
{
if(left<right)
{
int pivotIndex=(left+right)/2;
int pivot=partition(qArr, left, right, pivotIndex, qCount);
qSort(qArr, left, pivot-1, qCount);
qSort(qArr, pivot+1,right, qCount);
}
}
And here is the pivot function
int partition(int *qArr, int left, int right, int pivot, int *qCount)
{
int i;
int pivotValue=qArr[pivot];
int index=left;
swap(&qArr[pivot],&qArr[right]);
(*qCount)++;
for(i=left;i<right;i++);
{
if (qArr[i]<pivotValue)
{
swap(&qArr[i],&qArr[index]);
(*qCount)++;
index++;
}
}
swap(&qArr[index],&qArr[right]);
return index;
}
The sort must work in place, following closely to the pseudo-code provided on:
http://en.wikipedia.org/wiki/Quicksort
Thanks for your help!
Here is my output:
190 506 115 471 168 229 851 497 728 549 33 435 214 439 822 500 797 692 44 731 222 613 550 669 556 978 756 402 751 357 102 393 298 604 706 686 899 997 268 758 684 147 151 814 262 310 959 82 234 119 976 13 709 27 989 375 150 639 65 552 252 542 925 637 273 2 655 827 584 418 163 871 485 982 331 810 894 201 620 123 853 231 870 335 774 546 775 351 116 73
Obviously unsorted still :-D
You have a semicolon at the end of your for loop .. that loop body is only executed once.
for(i=left;i<right;i++);

Read file with strings and integers in matlab

I have to read a file in Matlab that looks like this:
D:\Classified\positive-videos\vid.avi 163 3 14 32 54 79 105 130 155 202 216 224 238 250 262 288 288 322 357 369 381 438 457 478 499 525 551
D:\Classified\positive-videos\vid2.avi 163 3 14 32 54 79 105 130 155 202 216 224 238 250 262 288 288 322 357 369 381 438 457 478 499 525 551
There are many such lines separated by newline. I need to read it such that: I discard path of video name and first integer(eg 163 in first line) and read rest all the numbers in an array till new line occurs. How can this be done?
You could do the following:
fid = fopen('test1.txt','r');
my_line = fgetl(fid);
while(my_line ~= -1)
my_array = regexp(my_line,' ','split');
my_line = fgetl(fid);
disp(my_array(3:end));
end
fclose(fid);
This would give you:
ans =
Columns 1 through 11
'3' '14' '32' '54' '79' '105' '130' '155' '202' '216' '224'
Columns 12 through 22
'238' '250' '262' '288' '288' '322' '357' '369' '381' '438' '457'
Columns 23 through 26
'478' '499' '525' '551'
ans =
Columns 1 through 11
'3' '14' '32' '54' '79' '105' '130' '155' '202' '216' '224'
Columns 12 through 22
'238' '250' '262' '288' '288' '322' '357' '369' '381' '438' '457'
Columns 23 through 26
'478' '499' '525' '551'
EDIT
For a numeric matrix result you can change it as:
clear;
close;
clc;
fid = fopen('test1.txt','r');
my_line = fgetl(fid);
my_array = regexp(my_line,' ','split');
my_matrix = zeros(0, numel(my_array(3:end)));
ii = 1;
while(my_line ~= -1)
my_array = regexp(my_line,' ','split');
my_line = fgetl(fid);
my_matrix = [my_matrix;zeros(1,size(my_matrix,2))];
for jj=1:numel(my_array(3:end))
my_matrix(ii,jj) = str2num(cell2mat(my_array(jj+2)));
end
ii = ii + 1;
end
fclose(fid);
This would yeild:
my_matrix =
3 14 32 54 79 105 130 155 202 216 224 238 250 262 288 288 322 357 369 381 438 457 478 499 525 551
3 14 32 54 79 105 130 155 202 216 224 238 250 262 288 288 322 357 369 381 438 457 478 499 525 551
A way easier method follows up:
fid = importdata(filename)
results = fid.data;
Ad maiora.
EDIT
Since you wanna discard the first value after the string, you will have to call
res = fid.data(:,2:end);
instead of results.

Resources