smallseo.info

c# interview questions

Top c# frequently asked interview questions

mongoLab C driver authentication and Basic Example

I am trying to interface Official C driver with mongoLab but getting error that failed to authenticate credentials. Do anyone have any simple example on how to interface mongolab using C driver. This is my example code

const char* String_uri = "mongodb://<username>:<pwd>@ds011115.mongolab.com:11115/tempdb";

    uri = mongoc_uri_new(String_uri);
    client = mongoc_client_new_from_uri (uri);


   collection = mongoc_client_get_collection (client, "mydb", "mycoll");
   doc = bson_new_from_json ((const uint8_t *)"{\"hello\" : \"world\"}", -1, &error);

   count = mongoc_collection_count (collection, MONGOC_QUERY_NONE, doc, 0, 0, NULL, &error);

   if (count < 0) {
      fprintf (stderr, "%s\n", error.message);
   } else {
      printf ("%" PRId64 "\n", count);
   }

Source: (StackOverflow)

Having trouble using a C library via a Python API: What am I doing wrong?

I'm using a Python script in conjunction with a thermocouple and a thermocouple reader. To communicate with the thermocouple reader, which is written in C, I have to use an API. That API is PyDAQFlex. The thermocouple reader also came with a tester script, written in C. I'm trying to get a temperature reading from the thermocouple reader, but it only outputs the CJC value.

My code:

import daqflex

d = daqflex.USB_2001_TC()

def get_temperature():
    return float(d.send_message("?AI{0}:CJC/DEGC").encode("utf-8"))

The output of my code:

u'AI{0}:CJC/DEGC=23.8'

Note: 23.8 is not the temperature. That value is the CJC, as seen in the tester script's command line output below. It's related, but not the value I'm looking for.


The tester script's code:

http://pastebin.com/Atsdy7X0 (to get the temperature, I press "t" and then "k" because I have a K-type thermocouple).

The tester script's command line output:

http://pastebin.com/jq4Rr4QX (the temperature here is accurate. This is what I want to plug into my script.)


The PyDAQFlex script:

https://github.com/torfbolt/PyDAQFlex/blob/master/daqflex/devices.py (see line 105)

The C code for the thermocouple reader:

http://pastebin.com/rEDR9efR (Not included in entirety, only the relevant parts.)


I am seriously struggling to see my mistake here. This exact piece of code appears to have worked for someone else in the PyDAQFlex Github page, so I'm extremely confused. I have emailed the creator of the software, a person in Github with a similar issue as me, and I just spent 6 hours in various IRC chats. Please help me. If it helps, I used parts of this tutorial to install the drivers and things for the thermocouple reader. Thank you so much.


Source: (StackOverflow)

Read the entire contents of a file to c char *, including new lines

I'm looking for a cross platform (Windows + Linux) solution to reading the contents of an entire file into a char *.

This is what I've got now:

FILE *stream;
char *contents;
fileSize = 0;

//Open the stream
stream = fopen(argv[1], "r");

//Steak to the end of the file to determine the file size
fseek(stream, 0L, SEEK_END);
fileSize = ftell(stream);
fseek(stream, 0L, SEEK_SET);

//Allocate enough memory (should I add 1 for the \0?)
contents = (char *)malloc(fileSize);

//Read the file 
fscanf(stream, "%s", contents);     

//Print it again for debugging
printf("Read %s\n", contents);

Unfortunately this will only print the first line in the file so I assume that fscanf stops at the first newline character. However I would like to read the entire file including, and preserving, the new line characters. I'd prefer not to use a while loop and realloc to manually construct the entire string, I mean there has to be a simpler way?


Source: (StackOverflow)

Tree: Level order Traversal using queue

I wrote codes that traversing tree using queue, but dequeue function below generates error, Is there any problem with head = p->next ? I cannot figure out why this part is wrong.

void Levelorder(void) {
node *tmp, *p;


if (root == NULL) return;

tmp = root;
printf("The level order is :\n");

while (tmp != NULL) {

    printf("%d, ", tmp->data);
    if (tmp->left) {
        enqueue(tmp->left);
    }
    if (tmp->right) {
        enqueue(tmp->right);
    }
    tmp = dequeue();
}

return;
}

void enqueue(node *p) {
if (head == NULL) {
    head = p;
}
else {
    tail->next = p;
}
tail = p;
p->next = NULL;
tail->next = NULL;

return;
}

node* dequeue(void) {
node *p;
p = head;
head = p->next;


if (head == NULL) {
    tail == NULL;
}

return p;
}

Source: (StackOverflow)

Mixing bitfields in structures

Hanging on geeksforgeeks about bitfields, found this example:

#include <stdio.h>
struct test
{
   unsigned int x;
   long int y: 33;
   unsigned int z;
};
int main()
{
   struct test t;
   unsigned int *ptr1 = &t.x;
   unsigned int *ptr2 = &t.z;
   printf("%d", ptr2 - ptr1);
   return 0;
}

As result, output is 4. But why? x occupies 4 bytes, y - 8, and z - 4. Difference in addresses x and z must be 8?


Source: (StackOverflow)

Using cmake to compile CSDP

I trying to use CSDP which is a mathematical library for SDP. I download the library an extract the lib (libsdp.a). It is using lapack and blas lib, so I add -lblas and -llapack options.

I want to compile with cmake, hier is my CmakeList file (I comment a lot of line, I just want to test the compilation of example.c with is an example given by CSDP) :

# Cette commande non obligatoire est fortement conseillée.
cmake_minimum_required (VERSION 2.6)

# Déclaration du projet.
# Les fichiers CMakeLists pourront référer à la racine du projet par la variable
# ${ECMA_SOURCE_DIR} et ${ECMA_BINARY_DIR}
project(projet_ECMA)
set(EXE run)

# L'exécutable sera rangé différemment en fonction de la plateformee.
# Par défaut le binaire est construit dans le répertoire courant (?)
# set(EXECUTABLE_OUTPUT_PATH ../bin)
# set( EXECUTABLE_OUTPUT_PATH bin/${CMAKE_BUILD_TYPE} )

#     SET (CMAKE_C_COMPILER             "/usr/bin/clang")
#     SET (CMAKE_C_FLAGS                "-Wall -std=c99")
#     SET (CMAKE_C_FLAGS_DEBUG          "-g++")
#     SET (CMAKE_C_FLAGS_MINSIZEREL     "-Os -DNDEBUG")
#     SET (CMAKE_C_FLAGS_RELEASE        "-O4 -DNDEBUG")
#     SET (CMAKE_C_FLAGS_RELWITHDEBINFO "-O2 -g")
#
#     SET (CMAKE_CXX_COMPILER             "/usr/bin/clang++")
#     SET (CMAKE_CXX_FLAGS                "-Wall")
#     SET (CMAKE_CXX_FLAGS_DEBUG          "-g")
#     SET (CMAKE_CXX_FLAGS_MINSIZEREL     "-Os -DNDEBUG")
#     SET (CMAKE_CXX_FLAGS_RELEASE        "-O4 -DNDEBUG")
#     SET (CMAKE_CXX_FLAGS_RELWITHDEBINFO "-O2 -g")
#
#     SET (CMAKE_AR      "/usr/bin/llvm-ar")
#     SET (CMAKE_LINKER  "/usr/bin/llvm-ld")
#     SET (CMAKE_NM      "/usr/bin/llvm-nm")
#     SET (CMAKE_OBJDUMP "/usr/bin/llvm-objdump")
#     SET (CMAKE_RANLIB  "/usr/bin/llvm-ranlib")

#set(CSDP_DIR "/home/hassan/Bureau/ECMA/projet_ECMA/trunk/lib/libsdp.a")
#find_package(CSDP REQUIRED)
SET (BLAS "/usr/lib/libcblas.a")
SET (LAPACK "/usr/lib/liblapack.a")
SET (CSDP "/home/hassan/Bureau/ECMA/projet_ECMA/trunk/lib/libsdp.a")
# Les options de compilation
# add_definitions(-Wall -Wextra -ansi -O2 -Wwrite-strings
#                 -Wuninitialized -Wno-missing-braces
#                 -Wno-missing-field-initializers)
add_definitions(
    # -Wno-unused-private-field  # Pour inhiber un warning de cplex 12.4
#    -m64
#    -g
#    -fPIC
#    -fexceptions
#    -pg
#    -DNDEBUG
#    -DIL_STD  # Pour cplex en C++
#    -std=c++11
#    -o
    -O3
#    -pthread
    #-L/home/hassan/Bureau/ECMA/projet_ECMA/trunk/lib    
    -ansi 
    -Wall
    -DNOSHORTS
    -DUSEGETTIME   
#    -lsdp

-lsdp -llapack
-latlas 
    -lcblas 
    -lgfortran
    -lm
-lg2c
-lctmg -lf2c

)

# Config spécifique à un système
# - UNIX vrai sous une plateforme Unix (don macosx)
# - APPLE vrai pour un os apple (donc macosx !)
# - WIN32 : vrai sous Windows (32 et 64bit !)
if(APPLE)
    message("=> Détection système Apple")
    set(CMAKE_EXE_LINKER_FLAGS  "-Wl,-no_compact_unwind")
endif()


# file(
#     GLOB
#     srcs
#     src/*.cpp
#     src/*.cc
#     src/*.c
#     src/*.hh
#     src/*.h
# )

# On définit la liste des tous les fichiers sources (dont les includes)
# cmale se débrouillera pour trouver le main() et les dépendances.
# On peut préciser des sous-répertoires, des groupes de fichiers, ...
# Mais ATTENTION aux fichiers inutilisés : ils seront compiler et peuvent
# provoquer des erreurs. Il peut donc être référable de préciser exactement les
# fichiers sources
file(
    GLOB
    srcs
    # src/site.*
    # src/station.*
    # src/remorque.*
    # src/arc.*
    # src/util.*
    # src/logger.*
    # src/options.*
    # src/bench.*
    # src/*Solver.*
    # src/solver.*
    # src/cir.*
    # src/solu.*
    # src/main.*
 #   src/*hpp
 #   /home/hassan/Bureau/ECMA/projet_ECMA/trunk/include/*.*
 #   src/*cpp
    src/*.cc
    src/*.hh
    src/example.c
    src/*.h
    # src/*.*
)

# Le ou les exécutables à générer
add_executable(${EXE} ${srcs})

# Les répertoire ou chercher vos includes (ou ceux de cplex, ...)
include_directories(
  # ${PROJECT_SOURCE_DIR}
  # ${PROJECT_BINARY_DIR}
  #$ENV{CONCERT_INCLUDE_DIR}
  $ENV{CSDP_INCLUDE}
  #$ENV{CPOPTIMIZER_INCLUDE_DIR}
  #$ENV{CPLEX_INCLUDE_DIR}
  # $ENV{LEMON_INCLUDE}
  #$ENV{CPOPTIM_INCLUDE_DIR}
  # $ENV{GLPK_INCLUDE}
)

# Ajouter ici les répertoires de vos bib. dynamiques utilisées
#

link_directories(
  # ${PROJECT_BINARY_DIR}/lemon
  # $ENV{LEMON_LIB}
  # $ENV{GLPK_LIB} 
   $ENV{CSDP_LIB} 
#  $ENV{CONCERT_LIB_DIR}
#  $ENV{CPLEX_LIB_DIR}
)

#find_library(CPLEX cplex HINTS $ENV{CPLEX_LIB_DIR})
#find_library(ILO_CPLEX ilocplex HINTS $ENV{CPLEX_LIB_DIR})
#find_library(CPOTIMIZER cpoptimizer HINTS $ENV{CPOPTIMIZER_LIB_DIR})
#find_library(CONCERT concert HINTS $ENV{CONCERT_LIB_DIR})
find_library(CSDP sdp HINTS $ENV{CSDP_LIB})

# Ajouter ici les bibliothèques dynamiques que vous utilisez
#
target_link_libraries(${EXE} blas)  # pour programmation multithead
target_link_libraries(${EXE} lapack)  # pour programmation multithead
#target_link_libraries(${EXE} sdp)  # pour programmation multithead
target_link_libraries(${EXE} pthread)  # pour programmation multithead
target_link_libraries(${EXE} m)        # lib mathématique
target_link_libraries(${EXE} ${ILO_CPLEX}) # spécial cplex
target_link_libraries(${EXE} ${CPLEX})    # spécial cplex
target_link_libraries(${EXE} ${CPOPTIMIZER})    # spécial cplex
target_link_libraries(${EXE} ${CONCERT})  # spécial cplex
message("=> CSDP     is   ${CONCERT}")
#target_link_libraries(${EXE} ${BLAS})  # spécial csdp
#target_link_libraries(${EXE} ${LAPACK})  # spécial csdp
target_link_libraries(${EXE} ${CSDP})  # spécial csdp

#target_link_libraries(${EXE} ${BLAS})  # spécial csdp
# target_link_libraries(${EXE} emon)   # lib de graphe
# target_link_libraries(${EXE} glpk)   # solveur PLNE gratuit




# La liste des exécutables mono-fichiers à compiler
## set(demo_srcs
##     main.cc
##     test1.cc
##     test2.cc
## )
# file(GLOB demo_srcs src/*.cc)


## foreach(demo_src ${demo_srcs})
##     get_filename_component( demo_name ${demo_src} NAME_WE )
##     message("=> demo_src=${demo_src}")
##     message("=> demo_name=${demo_name}")
##     add_executable(${demo_name} ${demo_src})
##     target_link_libraries(${demo_name} emon)
## endforeach()

# Quelques messages précisant la configuration utilisée
#
 message("=> CSDP_INCLUDE     is   $ENV{CSDP_INCLUDE}")
 message("=> CSDP_LIB     is   $ENV{CSDP_LIB}")
 message("=> ILOG_CPLEX_INCLUDE     is   $ENV{CPLEX_INCLUDE_DIR}")
 message("=> ILOG_CPLEX_LIB         is   $ENV{CPLEX_LIB_DIR}")
 message("=> ILOG_CONCERT_INCLUDE   is   $ENV{CONCERT_INCLUDE_DIR}")
 message("=> ILOG_CONCERT_LIB       is   $ENV{CONCERT_LIB_DIR}")
# message("=> LEMON_INCLUDE          is   $ENV{LEMON_INCLUDE}")
# message("=> LEMON_LIB              is   $ENV{LEMON_LIB}")
# message("=> GLPK_INCLUDE           is   $ENV{GLPK_INCLUDE}")
# message("=> GLPK_LIB               is   $ENV{GLPK_LIB}")
message("=> srcs                   is   ${srcs}")
# Ceci affiche 8 sur un machine 64 bits ou 4 sur un machine 32 bit
message("=> CMAKE_SIZEOF_VOID_P    is   ${CMAKE_SIZEOF_VOID_P}")
message("\n")



#
# Complément pour ajouter quelques cibles personnalisées dans le Makefile généré
#
EXECUTE_PROCESS(
    COMMAND date +%Y%m%d-%Hh%M
    OUTPUT_VARIABLE date_stamp
    OUTPUT_STRIP_TRAILING_WHITESPACE
)
GET_FILENAME_COMPONENT( project_dir_name ${CMAKE_SOURCE_DIR} NAME )


# On peut compléter les cible du Makefile généré
# (la comande finale de cette ciblesera ajoutée à CMakeFiles/Makefile2)
# (puis Essayer de créer un cmake tbz !!)
ADD_CUSTOM_TARGET(distclean
    COMMAND @echo Nettoyage complet des sources
    COMMAND @echo \"Répertoire courant = `pwd`\"
    COMMAND @echo "CMAKE_CURRENT_BINARY_DIR=${CMAKE_CURRENT_BINARY_DIR}"
    # COMMAND make clean
    COMMAND find ${CMAKE_CURRENT_BINARY_DIR} -name "CMakeCache.txt" | xargs rm -rf
    COMMAND rm -rf ${CMAKE_CURRENT_BINARY_DIR}/*
)
ADD_CUSTOM_TARGET(dc
    COMMAND make distclean
)
ADD_CUSTOM_TARGET(cc
    COMMAND make distclean
)
ADD_CUSTOM_TARGET(c
    COMMAND make clean
)
# Attention : cette commande construit une cible pour le Makefile.
# Il faut protéger les double-quote si l'on veux qu'elles ne soient pas consommées
# par cmake mais passée au Makefile.
# Un seul COMMENT par cible semble-t-il
ADD_CUSTOM_TARGET(tbz
    COMMENT "Création d'une archive datée du projet"
    COMMAND @echo \" => duplication du projet en : ${project_dir_name}-${date_stamp}\"
    COMMAND cp -Rp ${CMAKE_SOURCE_DIR} ${CMAKE_SOURCE_DIR}-${date_stamp}
    COMMAND rm -r ${CMAKE_SOURCE_DIR}-${date_stamp}/build/
    COMMAND mkdir -p ${CMAKE_SOURCE_DIR}-${date_stamp}/build/
    # tar -C newDir :  pour se placer dans le répertoire parent de l'archive
    COMMAND tar cjf  ${CMAKE_SOURCE_DIR}-${date_stamp}.tbz
                     -C ${CMAKE_SOURCE_DIR}/..
                     ${project_dir_name}-${date_stamp}
    COMMAND rm -r ${CMAKE_SOURCE_DIR}-${date_stamp}
    COMMAND @echo \" => Archive faite :  ${project_dir_name}-${date_stamp}.tbz\"
)
ADD_CUSTOM_TARGET(txz
    COMMENT "Création d'une archive datée du projet (TEST XZ)"
    COMMAND @echo \" => duplication du projet en : ${project_dir_name}-${date_stamp}\"
    COMMAND cp -Rp ${CMAKE_SOURCE_DIR} ${CMAKE_SOURCE_DIR}-${date_stamp}
    COMMAND rm -r ${CMAKE_SOURCE_DIR}-${date_stamp}/build/
    COMMAND mkdir -p ${CMAKE_SOURCE_DIR}-${date_stamp}/build/
    # tar -C newDir :  pour se placer dans le répertoire parent de l'archive
    COMMAND tar cf  ${CMAKE_SOURCE_DIR}-${date_stamp}.tar
                     -C ${CMAKE_SOURCE_DIR}/..
                     ${project_dir_name}-${date_stamp}
    COMMAND xz  ${CMAKE_SOURCE_DIR}-${date_stamp}.tar
    COMMAND mv    ${CMAKE_SOURCE_DIR}-${date_stamp}.tar.xz ${CMAKE_SOURCE_DIR}-${date_stamp}.txz
    COMMAND rm -r ${CMAKE_SOURCE_DIR}-${date_stamp}
    COMMAND @echo \" => Archive faite :  ${project_dir_name}-${date_stamp}.tbz\"
)
# ADD_CUSTOM_TARGET(zip
#     COMMENT "Création d'une archive datée du proje (TEST ZIP°t"
#     COMMAND @echo \" => duplication du projet en : ${project_dir_name}-${date_stamp}\"
#     COMMAND cp -Rp ${CMAKE_SOURCE_DIR} ${CMAKE_SOURCE_DIR}-${date_stamp}
#     COMMAND rm -r ${CMAKE_SOURCE_DIR}-${date_stamp}/build/
#     COMMAND mkdir -p ${CMAKE_SOURCE_DIR}-${date_stamp}/build/
#     COMMAND echo \"1: CMAKE_SOURCE_DIR-date_stamp==1==${CMAKE_SOURCE_DIR}-${date_stamp}\"
#     COMMAND echo \"2: project_dir_name-date_stamp==2==${project_dir_name}-${date_stamp}\"
#     # tar -C newDir :  pour se placer dans le répertoire parent de l'archive
#     # COMMAND '_pwd=`pwd`'
#     # COMMAND pushd  ${CMAKE_SOURCE_DIR}/..
#     COMMAND echo 'pushd; zip -r -v -y -o -9  ${CMAKE_SOURCE_DIR}-${date_stamp}.zip \
#                      ${project_dir_name}-${date_stamp} ; popd'
#     COMMAND sh -c "pushd; zip -r -v -y -o -9  ${CMAKE_SOURCE_DIR}-${date_stamp}.zip \
#                      ${project_dir_name}-${date_stamp} ; popd"
#     # COMMAND zip -r -v -y -o -9  ${CMAKE_SOURCE_DIR}-${date_stamp}.zip
#     #                  ${project_dir_name}-${date_stamp}
#     COMMAND 'cd $_pwd'
#     # COMMAND popd
#     COMMAND rm -r ${CMAKE_SOURCE_DIR}-${date_stamp}
#     COMMAND @echo \" => Archive faite :  ${project_dir_name}-${date_stamp}.tbz\"
# )

INCLUDE(InstallRequiredSystemLibraries)
IF(WIN32 AND NOT UNIX)
    SET(CPACK_NSIS_MODIFY_PATH ON)
ENDIF(WIN32 AND NOT UNIX)

INCLUDE(CPack)

#./

The problem is, I think that libsdp.a need library (blas, lapack and math) but, even if I add it in my Cmake, he don't succeed to find it :

    [100%] Building C object CMakeFiles/run.dir/src/example.c.o
/usr/bin/cc  -DNOSHORTS -DUSEGETTIME -I/home/hassan/Bureau/ECMA/projet_ECMA/trunk/include    -O3 -ansi -Wall -lsdp -llapack -latlas -lcblas -lgfortran -lm -lg2c -lctmg -lf2c -o CMakeFiles/run.dir/src/example.c.o   -c /home/hassan/Bureau/ECMA/projet_ECMA/src/example.c
/home/hassan/Bureau/ECMA/projet_ECMA/src/example.c: In function ‘main’:
/home/hassan/Bureau/ECMA/projet_ECMA/src/example.c:62:2: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘double’ [-Wformat=]
  printf("%d \n", sqrt(2));
  ^
Linking C executable run
/usr/bin/cmake -E cmake_link_script CMakeFiles/run.dir/link.txt --verbose=1
/usr/bin/cc      CMakeFiles/run.dir/src/example.c.o  -o run -rdynamic -lblas -llapack -lpthread -lm trunk/lib/libsdp.a 
trunk/lib/libsdp.a(initsoln.o): dans la fonction « initsoln »:
initsoln.c:(.text+0x2a9): référence indéfinie vers « sqrt »
initsoln.c:(.text+0x2ed): référence indéfinie vers « sqrt »
initsoln.c:(.text+0x334): référence indéfinie vers « sqrt »
trunk/lib/libsdp.a(norms.o): dans la fonction « norm2 »:
norms.c:(.text+0x1d): référence indéfinie vers « dnrm2_ »
trunk/lib/libsdp.a(norms.o): dans la fonction « norm1 »:
norms.c:(.text+0x4d): référence indéfinie vers « dasum_ »
trunk/lib/libsdp.a(norms.o): dans la fonction « norminf »:
norms.c:(.text+0x81): référence indéfinie vers « idamax_ »
trunk/lib/libsdp.a(sdp.o): dans la fonction « sdp »:
sdp.c:(.text+0x1ed7): référence indéfinie vers « dpotrf_ »
sdp.c:(.text+0x2104): référence indéfinie vers « pow »
sdp.c:(.text+0x7cf3): référence indéfinie vers « sqrt »
sdp.c:(.text+0x8651): référence indéfinie vers « sqrt »
sdp.c:(.text+0x88eb): référence indéfinie vers « sqrt »
sdp.c:(.text+0x88f5): référence indéfinie vers « sqrt »
sdp.c:(.text+0x8968): référence indéfinie vers « pow »
sdp.c:(.text+0x89bd): référence indéfinie vers « sqrt »
sdp.c:(.text+0x89e9): référence indéfinie vers « sqrt »
trunk/lib/libsdp.a(Fnorm.o): dans la fonction « Fnorm »:
Fnorm.c:(.text+0xcb): référence indéfinie vers « sqrt »
trunk/lib/libsdp.a(calc_dobj.o): dans la fonction « calc_dobj »:
calc_dobj.c:(.text+0x2d): référence indéfinie vers « ddot_ »
trunk/lib/libsdp.a(mat_mult.o): dans la fonction « mat_mult »:
mat_mult.c:(.text+0xef): référence indéfinie vers « dgemm_ »
trunk/lib/libsdp.a(mat_mult.o): dans la fonction « mat_mult_raw »:
mat_mult.c:(.text+0x479): référence indéfinie vers « dgemm_ »
trunk/lib/libsdp.a(solvesys.o): dans la fonction « solvesys »:
solvesys.c:(.text+0x40): référence indéfinie vers « dpotrs_ »
trunk/lib/libsdp.a(linesearch.o): dans la fonction « linesearch »:
linesearch.c:(.text+0x39f): référence indéfinie vers « dgemv_ »
linesearch.c:(.text+0x416): référence indéfinie vers « dgemv_ »
linesearch.c:(.text+0x488): référence indéfinie vers « dgemv_ »
linesearch.c:(.text+0x4ff): référence indéfinie vers « dgemv_ »
linesearch.c:(.text+0xe2b): référence indéfinie vers « sqrt »
trunk/lib/libsdp.a(matvec.o): dans la fonction « matvec »:
matvec.c:(.text+0xb8): référence indéfinie vers « dgemv_ »
trunk/lib/libsdp.a(chol.o): dans la fonction « chol_blk »:
chol.c:(.text+0x36): référence indéfinie vers « dpotrf_ »
trunk/lib/libsdp.a(chol.o): dans la fonction « chol_diag »:
chol.c:(.text+0x134): référence indéfinie vers « sqrt »
trunk/lib/libsdp.a(chol.o): dans la fonction « chol »:
chol.c:(.text+0x1bd): référence indéfinie vers « dpotrf_ »
chol.c:(.text+0x2e1): référence indéfinie vers « sqrt »
trunk/lib/libsdp.a(chol.o): dans la fonction « chol_inv »:
chol.c:(.text+0x42f): référence indéfinie vers « dtrtri_ »
trunk/lib/libsdp.a(qreig.o): dans la fonction « qreig »:
qreig.c:(.text+0x539): référence indéfinie vers « sqrt »
qreig.c:(.text+0x64f): référence indéfinie vers « sqrt »
qreig.c:(.text+0x718): référence indéfinie vers « sqrt »
collect2: error: ld returned 1 exit status
make[2]: *** [run] Erreur 1

Source: (StackOverflow)

Pass to Value in C math

I am just learning C. i am working through this problem trying to predict the output:

#include <stdio.h>

int gNumber;
int MultiplyIt( int myVar );

int main (int argc, const char * argv[])
{
    int i; gNumber = 2;
    for ( i = 1; i <= 2; i++ )
        gNumber *= MultiplyIt( gNumber );
    printf( "Final value is %d.\n", gNumber );
    return 0;
}

int MultiplyIt( int myVar )
{
    return( myVar * gNumber );
}

so if you run this, the output is 512. i am a bit confused on how the calculation is getting from the initial value of 2, then first time through the 'for' loop it then assigns gNumber = 8. then jumps to 512...

maybe i am missing something easy here, but as i said, i am very new to C and programing in general..


Source: (StackOverflow)

I was given this to do in c. someone help me? [on hold]

This is how the question is:

Description: RAM on a computer is a finite resource. Sometimes we simply don’t have enough to perform the calculations we wish to perform. Just as user input might be mal-formed and can cause programs to crash, requesting more RAM than is available will also cause our programs to crash.

General Requirements:

Write a program that starts with a variable holding the value 1 million and iteratively tries to allocate an array of integers of that size.

Increase the size by one million each time through the loop.

At each iteration check to see if the allocation was successful.

Remember to deallocate the memory within the loop before proceeding to the next iteration.

Report the biggest successful allocation to the user.

Note: determine beforehand if a 32bit integer is big enough to hold the array size? If not, what type of variable can you use?

Monitor the memory usage in your task manager as your program runs.

What do you see happening? What would happen to other programs if your program never de-allocated its memory?

Does your reported memory size for the largest allocation make sense given the total amount of RAM on your machine? Are you using a properly sized integer for the allocation size given the total RAM on your machine?


Source: (StackOverflow)

How to randomize lowest bits in a 64 bit pattern

I am interested in learning more about the concepts behind bit shifting and the manipulation of randomly generated bits. Below is some code that prints 20 random 64 bit patterns. "rand_bits" uses the C standard rand() to return a 64 bit pattern with all zeros except for the lowest bits, which are randomized. The number of low randomized bits is provided by the only parameter to the function.

   const int LINE_CNT = 20;

    void print_bin(uint64_t num, unsigned int bit_cnt);

    uint64_t rand_bits(unsigned int bit_cnt);

    int main(int argc, char *argv[]) {

        int i;

        srand(time(NULL));
        for(i = 0; i < LINE_CNT; i++) {
            uint64_t val64 = rand_bits(64);
            print_bin(val64, 64);
        }
    return EXIT_SUCCESS;
    }


    void print_bin(uint64_t num, unsigned int bit_cnt) {

        int top_bit_cnt;

        if(bit_cnt <= 0) return;
        if(bit_cnt > 64) bit_cnt = 64;

        top_bit_cnt = 64;
        while(top_bit_cnt > bit_cnt) {
            top_bit_cnt--;
            printf(" ");
        }

        while(bit_cnt > 0) {
            bit_cnt--;
            printf("%d", (num & ((uint64_t)1 << bit_cnt)) != 0);
        }
        printf("\n");

        return;
    }


    /*
     * Name: rand_bits
     * Function: Returns a 64 bit pattern with all zeros except for the
     *           lowest requested bits, which are randomized.  
     * Parameter, "bit_cnt":  How many of the lowest bits, including the
     *           lowest order bit (bit 0) to be randomized
     * Return: A 64 bit pattern with the low bit_cnt bits randomized.
     */
    uint64_t rand_bits(unsigned int bit_cnt) {


        printf("int bit_cnt:", bit_cnt);
        uint64_t result = rand();
        uint64_t result_1 = result>>5;
// uint64_t result_1 = result>>7;

//return result;
        return result_1;

    }

For example, if the function is called with 24 as the argument value, it might return a 64 bit pattern, such as:

0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_​1101_0110_0101_1110_0111_1100

Currently the function rand_bits may show more than 15 random bits coming from the rand() function, but this is by NO means guaranteed.

I thought that to get the 40 bits like in the example I could right shift the bits, but that does not seem to be the concept. Does this require a bit mask of the higher order bits or a mod calculation on the random number generator?

Any suggestions of how to return a bit pattern of all zeros with its lowest bits (bit_cnt) randomized?


Source: (StackOverflow)

Have an Issue with c program execution

I'm not sure what issue I am having when executing this code Outputs error "/usr/lib/gcc/x86_64-redhat-linux/4.9.2/../../../../lib64/crt1.o: In function _start':
(.text+0x20): undefined reference to
main'
collect2: error: ld returned 1 exit status"
Here is the code

#include <stdio.h>
int get_input(void);
int is_valid(int);
void print_pattern(int);
int main(void);
/* asks the user for an odd integer between 1 and 9
 * stores the integer
 * returns the number input by the user no matter if it fits the perameters    or not
 */

int get_input(void){
int n;
do{
printf("Enter and odd number less than or equal to 9 and greater than 0 >");
scanf("%d", &n);
}
while(is_valid(n) == 0);
return n;
}
/*
* checks to see if the integer entered by the user is even 
* and checks to see if the number is greater than 0 and less than 10
*/
int is_valid(int x){
if (x==1 || x==3 || x==5 || x==7 || x==9){
return 1;
}
else{
if(x<1){
printf("You have entered a number less than 1. Please try agian."); 
return 0;
}
if(x>9){
printf("You have entered a number greater than 9. Please try agin.");
return 0;
}
else{
printf("You have entered an even number. Please try agian.");
return 0;
}
} 

void print_pattern(int n){
int c, i, space, q, b, l, j;
space = n-1;

 for(i=1; i <= n; ++i){
 for(c=1; c <= space; ++c)
 printf(" ");
 space--;
 for(q=1; q <= 2*i-1; ++q)
 printf("%d", q);
 printf("\n");
 }

 space=1; 
 for(b=1; b <= n-1; ++b){
  for (l=1; l <= space; l++)
 printf(" ");
 space++;
 for(j=1; j <= 2*(n-b)-1; ++j)
 printf("%d", j);
 printf("\n");
 }
 }
 int main(void){
 int z = get_input();
 print_pattern(z);
 return 0;
 }}

Source: (StackOverflow)

Pointer Declaration Equivalency

char *charPtr = malloc(50);

char *charPtr; *charPtr = malloc(50);

I have been creating pointers in C like the examples above. Is it okay to say that these two are the same in C?


Source: (StackOverflow)

Can the stringize macro be used here?

Using Pelles C I would like to show or log an unsigned char array. Is it possible to use the stringize macro to show the whole array as hex values instead of iterating through the array with printf(%x)?


Source: (StackOverflow)

I want a c programme that asks the user to input some n number of strings and the output should be the n strings

Iam getting an error that executable stopped working.Please help me .It is very important for me.


Source: (StackOverflow)

Read scientific notation scanf

I am developing a program which should have only one scanf function and it should be able to accept input in scientific notation and real numbers.

Any help will be appreciated


Source: (StackOverflow)

Why are my ASCII integer values becoming negative?

I am trying to do a very basic form of encryption and decryption by using operations on ASCII characters in C. I have the following code:

char* myEncrypt(char* stringToEncrypt)
{
    char *encryptedString = malloc(256);
    strcpy(encryptedString, stringToEncrypt);

    int publicKey = 50;

    for (int i = 0; encryptedString[i] && encryptedString[i] != '\n'; ++i)
            encryptedString[i] = (encryptedString[i] + publicKey) % 256;

    return encryptedString;
}

My issue is that when I run this code I am every so often getting negative values for my integer values of the ASCII characters assigned to encryptedString[i]. This is causing the decryption to fail. Looking at the code there should be no way for me to get negative values since I am using the modulo operation. Am I missing something simple here?


Source: (StackOverflow)