c,pointers,computer-science,user-defined-functions , How to properly pass array pointers to function in C


How to properly pass array pointers to function in C

Question:

Tag: c,pointers,computer-science,user-defined-functions

A different question may have been asked about this program, however in this C code I have three functions: one to print records, one to add a record and one to delete a record.

What I don't understand is why the (add) and (delete) do not make changes in the main function, so when I use the print all records function it prints changes, but it doesn't show changes, what is wrong?

Details are in the comments, please feel free to run the code to visualise the problem.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/*The program is to store student record (firstname,lastname and score), it should not be more
than 15 records and the names should not be more than 20 chars, array pointersnare being used
instead of arrays, the (add_record) and (delete_record) functions must
do thsi change in the main function, so when you print all records, the changes are shown*/

void print_records(char **firstname,char **lastname,float *score,int *the_size)
{
    int i;
    printf("Printing All record(s)...\n");

    for (i=0;i<*the_size;i++) /*loop to print records of all arrays in correct format*/
    {
        printf("Firstname : %s, Lastname : %s, Score : %f\n",firstname[i],lastname[i],score[i]);

    }
}
void add_new_record (char **firstname,char **lastname,float *score,int the_size)
{
    printf("Add new record in the format :\nFirstname Lastname Score\n");
    /*the strategy here is to check if all 15 elemts are used, if they are, use realloc
    to add one more, if not add the record after the last record*/
    if (the_size == 15)
    {
        firstname=realloc(firstname,16*sizeof(char*));
        firstname[15]=malloc((20+1)*sizeof(char));
        lastname=realloc(lastname,16*sizeof(char*));
        lastname[15]=malloc((20+1)*sizeof(char));
        score=realloc(score,16*sizeof(float));
        scanf("%s %s %f",firstname[15],lastname[15],&score[15]);
        printf("New Record Added Successfully !\n");
        printf("Firstname : %s, Lastname : %s, Score : %f\n",firstname[15],lastname[15],score[15]);
    }
    else if (the_size<15)
    {
        scanf("%s %s %f",firstname[the_size],lastname[the_size],&score[the_size]);
        printf("New Record Added Successfully !\n");
        printf("Firstname : %s, Lastname : %s, Score : %f\n",firstname[the_size],lastname[the_size],score[the_size]);
    }
}
void delete_record (char **firstname,char **lastname,float *score,int the_size)
{
    char *str=malloc(20*sizeof(char)); /*String entered by user must be 20 or less chars*/
    int i,ctr=0;
    char *temp_first=malloc(20*sizeof(char));/*temp array to swap firstname must be 20 or less chars*/
    char *temp_last=malloc(20*sizeof(char)); /*temp array to swap lastname must be 20 or less chars*/
    float temp_score;/*ctr is the counter used to check if there are no matchs in the end*/
    printf("Enter the lastname of record(s) to delete : ");
    scanf("%s",str);
    /* the strategy here is to move the element to be deleted to the last index and use
    relloc to shrink the size by 1 (-1) */
    for (i=0;i< the_size;i++)
    {
        if (strcmp(str,lastname[i])==0)
        {
            printf("Deleting Record for %s %s...\n",firstname[i],lastname[i]);
            temp_score=score[i];
            score[i]=score[the_size-1];
            score[the_size-1]=temp_score;
            strcpy(temp_first, firstname[i]);  /*using strcpy function to swap strings*/
            strcpy(firstname[i], firstname[the_size-1]);
            strcpy(firstname[the_size-1], temp_first);
            strcpy(temp_last, lastname[i]);
            strcpy(lastname[i], lastname[the_size-1]);
            strcpy(lastname[the_size-1], temp_last);
            score=realloc(score,(the_size-1)*sizeof(float));
            firstname=realloc(firstname,(the_size-1)*sizeof(char*));
            lastname=realloc(lastname,(the_size-1)*sizeof(char*));
            ctr++;
            the_size--;


            }

        }
    if (!ctr) /*if ctr=0 (no increment), then print,there is no match*/
    {
        printf ("Sorry, no available record for %s",str);
    }
        free(temp_first);
        free(temp_last);
        free(str);
}
void main()
{
    char **firstname;
    char **lastname;
    float *score;
    int number_of_records,i,j=-1,ctr=1,row=15,col=20;
    /*ctr is to keep track of the student's number (makes it easier to
      the user), it starts with (1)*/

    firstname=malloc(row*sizeof(char*));
    for(i=0;i<row;i++)
    {
        firstname[i]=malloc((col+1)*sizeof(char));
    }
     lastname=malloc(row*sizeof(char*));
    for(i=0;i<row;i++)
    {
        lastname[i]=malloc((col+1)*sizeof(char));
    }
    printf("\nPlease indicate number of records you want to enter (min 2, max 15): ");
    scanf("%d",&number_of_records);
    score=malloc(row*sizeof(float));

    printf("\nPlease input records of students\n(enter a new line after"
           "each record), with following format:\nfirst name last name score ");
    for (i=0;i<number_of_records;i++)
    {
        printf("\nEnter record for student %d : ",ctr);
        scanf("%s %s %f",firstname[i],lastname[i],&score[i]);

        ctr++; /*ctr is to keep track of student number
                 (makes it easy to the user) */

    }


    while (j!=0) /*Main menu will keep looping after using a function as long as j is not 0
           When the user enters 0 (zero) the loop will stop and therefore the program will terminate*/
    {
        printf("\nSelect desired function by pressing the corresponding key number\n");

        printf("\n********** Main Menu **********\n");

        printf("\n>>> Print records (press 1)\n");

        printf("\n>>> Add a new Record (press 2 )\n");

        printf("\n>>> delete record (press 3)\n");


        printf("\n>>> Exit the program (press 0)\n");

        scanf("%d",&j); /*getting j from the user (j is used for selection and for the while loop)*/
        if (j==1)
        {
            print_records(firstname,lastname,score,&number_of_records);
        }
        else if (j==2)
        {
        add_new_record(firstname,lastname,score,number_of_records);
        }
        else if (j==3)
        {
    delete_record(firstname,lastname,score,number_of_records);
        }
    else if (j==0)
    {
    printf("Exitting program ...\n");
        }
    }
}

Answer:

As other answers have observed, in C, all arguments are passed by value. That means the function gets a copy of the caller's value, therefore changes to that value are not visible to the caller. In other words, given

void f(any_type arg) {
    arg = any_value;
}

The caller will never detect any change, regardless of what type any_type is or what value any_value is. Note carefully, however, the difference between that, and this:

void f(any_type *arg) {
    *arg = any_value;
}

In that case, it is not the function argument (a pointer) that is being modified, it is the thing pointed to. The argument is a copy of the caller's value, so the two point to the same thing. The caller cannot detect changes to the argument, but after the call, it can detect changes to the thing it points to.

Your code exhibits some issues of this type, some of them responsible for your main problems. Most importantly, these have to do with your record keeping on the number of elements in your list (variable number_of_records in main()). Your addition and deletion functions work more or less ok, except that they cannot communicate the revised list size back to main.

There are additional issues in add_new_record() when there are already 15 records; if you can, I would just disallow that case. If you must support it, then you have multiple things to clean up. Some of them to do with pass-by-value issues, others to do with what your code should do when the list initially contains 16 or more records.

Update: Since you're having so much trouble working this out, here's a revised version of delete_record(). It implements a lot more than the minimal changes required to get the desired output upon record deletion, as there was in fact a goodly number of other issues that I might as well call out as long as I'm going to the trouble. See new and modified comments.

/*
 * Can realloc() *firstname, *lastname, and *score and return the updated
 * values to the caller.  Most importantly, can update *the_size and have
 * the caller see the result.
 */
void delete_record (char ***firstname, char ***lastname, float **score, int *the_size)
{
    int i;
    int initial_size = *the_size;
    char str[21];  /* no need to malloc a fixed-length local array */

    printf("Enter the lastname of record(s) to delete : ");
    fflush(stdout);  /* The prompt might not appear if you don't flush */
    /*
     * Note the field width in the format below.  Without it, a user can
     * easily cause a buffer overflow.
     */
    scanf("%20s", str);

    /*
     * The strategy for each element to delete (there may be more than one)
     * is to free the element's name components (else their allocated memory
     * leaks), copy the last (at that time) element's components into
     * place (for the name components, just the pointers), and later
     * realloc to shrink the overall size to exactly fit the remaining
     * elements (once we know how many that is).
     */
    for (i = 0; i < *the_size; )
    {
        if (strcmp(str, (*lastname)[i]) == 0)
        {
            printf("Deleting Record for %s %s...\n", (*firstname)[i], (*lastname)[i]);
            free((*firstname)[i]);
            free((*lastname)[i]);
            (*firstname)[i] = (*firstname)[*the_size - 1];
            (*lastname)[i] = (*lastname)[*the_size - 1];
            (*score)[i] = (*score)[*the_size - 1];
            *the_size -= 1; /* not the same as *the_size-- */
            /* don't increment i, else we miss testing the new i'th element */
        } else {
            i += 1;
        }
    }
    if (*the_size != initial_size)
    {
        void *temp;

        /*
         * Always check the return value of realloc(), even when you're
         * shrinking the allocation.  Usually, though, you'd want at least
         * some kind of diagnostic in the event of failure.
         */
        temp = realloc(*firstname, sizeof(char *) * (*the_size));
        if (temp)
        {
            *firstname = temp;
        }
        temp = realloc(*lastname, sizeof(char *) * (*the_size));
        if (temp)
        {
            *lastname = temp;
        }
        temp = realloc(*score, sizeof(float) * (*the_size));
        if (temp)
        {
            *score = temp;
        }
    }
    else  /* there is no match */
    {
        printf ("Sorry, no available record for %s",str);
    }
}

Your main() would call that like so:

delete_record(&firstname, &lastname, &score, &number_of_records);

Similar changes are needed to add_record(), though you do have the separate issue I already called out there with increasing the number of entries past 16.

Additionally, you're making extra work for yourself by using separate arrays of first name, last name, and score. It would be much easier to define a struct encompassing all three, and use just one dynamic array whose elements are instances of that struct.


Related:


Passing iterator's element to a function: wrong type of pointer


c++,pointers,stl,iterator
I'm attempting to solve Project Euler's problem #3 using C++ to gain an understanding of how to use C++ iterators. According to the examples I've seen online, I can use the dereferened iterator as a parameter for cout, and it will print the elements successfully. By that same logic, I...

C binary tree sort - extending it


c,binary-tree,binary-search-tree
I need some help in C Help me to extend the binary tree sort on C. I need to return a sorted array in sort function. here it is: #include <stdio.h> #include <stdlib.h> struct btreenode { struct btreenode *leftchild ; int data ; struct btreenode *rightchild ; } ; void...

execl() works on one of my code, but doesn't work on another


c,execl
I already used execl() in code, and it worked well. But this time, I really have no idea why it doesn't work. So here's the code that do not work #include <unistd.h> #include <stdio.h> int main() { int i = 896; printf("please\n"); execl("home/ubuntu/server/LC/admin/admin", (char*)i, NULL); printf("i have no idea why\n");...

getchar() not working in c


c,while-loop,char,scanf,getchar
getchar() is not working in the below program, can anyone help me to solve this out. I tried scanf() function in place of getchar() then also it is not working. I am not able to figure out the root cause of the issue, can anyone please help me. #include<stdio.h> int...

How to increment the value of an unsigned char * (C)


c++,c,openssl,byte,sha1
I have a value stored as an unsigned char * (in C). This holds the SHA1 hash of a string. My goal is to cover the SHA1 key space. Since I'm using <openssl/evp.h> to generate the hashes, I end up with an unsigned char* holding the SHA1 value. Now I...

scanf get multiple values at once


c,char,segmentation-fault,user-input,scanf
I need to get in one single shot different inputs from one single line. In particular I need to get a single char and then, depending on which char value I just read, it can be a string and an int or a string, an int and another string and...

Segmentation fault with generating an RSA and saving in ASN.1/DER?


c,openssl,cryptography,rsa
#include <string.h> #include <openssl/aes.h> #include <openssl/rand.h> #include <openssl/bio.h> #include <openssl/rsa.h> #include <openssl/evp.h> #include <openssl/pem.h> #define RSA_LEN 2048 #define RSA_FACTOR 65537 int genRSA2048(unsigned char **pub,unsigned int *pub_l,unsigned char **priv,unsigned int *priv_l){ RSA *pRSA = NULL; pRSA = RSA_generate_key(RSA_LEN,RSA_FACTOR,NULL,NULL); if (pRSA){ pub_l = malloc(sizeof(pub_l)); *pub_l = i2d_RSAPublicKey(pRSA,pub); priv_l = malloc(sizeof(priv_l));...

C++ / C #define macro calculation


c++,c,macros
Suppose I have #define DETUNE1 sqrt(7)-sqrt(5) #define DETUNE2 sqrt(11)-sqrt(7) And I call these multiple times in my program. Are DETUNE1 and DETUNE2 calculated every time it is called? Thanks. Please don't downvote this, I really want to know and a search didn't turn up anything definite. ...

Array breaking in Pebble C


c,arrays,pebble-watch,cloudpebble
I'm trying to create a simple dice-rolling application in Pebble using C on CloudPebble. I have an array of different die sizes you can scroll through using Up/Down, and you roll (currently just generate a random number, it'll get fancier later) using the middle button. There's also a label at...

CGO converting Xlib XEvent struct to byte array?


c,go,xlib,cgo
I am creating a simple window manager (code based of the c code in tinywm) in Golang. To use Xlib, I am using cgo, so my header is: // #cgo LDFLAGS: -lX11 // #include <X11/Xlib.h> And I have a variable declaration, like: event := C.XEvent{} And then, I use this...

What does `strcpy(x+1, SEQX)` do?


c,strcpy
I'm wondering what this syntax of strcpy() does in line 65 and 66: 24 #define SEQX "TTCATA" 25 #define SEQY "TGCTCGTA" 61 M = strlen(SEQX); 62 N = strlen(SEQY); 63 x = malloc(sizeof(char) * (M+2)); /* +2: leading blank, and trailing \0 */ 64 y = malloc(sizeof(char) * (N+2)); 65...

Is it safe to read and write on an array of 32 bit data byte by byte?


c,memory,memory-alignment
So I have a void * data of 32 bit unsigned integers which represents the pixels. Is it okay for me to access one of the pixels with a char * and modify the values directly? Or is it better to store my new pixel in a temporary uint32_t variable...

free causing different results from malloc


c,string,malloc,free
Below is a C program i have written to print different combination of characters in a string. This is not an efficient way as this algorithm creats a lot of extra strings. However my question is NOT about how to solve this problem more efficiently. The program works(inefficiently though) and...

Does realloc() invalidate all pointers?


c,pointers,dynamic-memory-allocation,behavior,realloc
Note, this question is not asking if realloc() invalidates pointers within the original block, but if it invalidates all the other pointers. I'm new to C, and am a bit confused about the nature of realloc(), specifically if it moves any other memory. For example: void* ptr1 = malloc(2); void*...

CallXXXMethod undefined using JNI in C


java,c,jni
So I've tried to use the JNI interface to call Java methods from C. Calling static methods is no problem, but I get stuck when I want to call a method on an object. The code is as follows: #include <stdio.h> #include <string.h> #include <jni.h> int main() { JavaVMOption options[1];...

What all local variables goto Data/BSS segment?


c++,c,nm
The man page of nm here: MAN NM says that The symbol type. At least the following types are used; others are, as well, depending on the object file format. If lowercase, the symbol is usually local; if uppercase, the symbol is global (external) And underneath it has "b" and...

Function pointer to singleton class instance function


c++,oop,pointers,singleton
What I'm trying to do is create a function pointer to a single class instance function. I want to do this so I can do something like this: C->member_method(); instead of: Config::inst()->member_method(); but I'm not sure how to go about it. Here is my singleton class: class Config { private:...

Does strlen() always correctly report the number of char's in a pointer initialized string?


c,strlen
As long as I use the char and not some wchar_t type to declare a string will strlen() correctly report the number of chars in the string or are there some very specific cases I need to be aware of? Here is an example: char *something = "Report all my...

Reverse ^ operator for decryption


c,algorithm,security,math,encryption
I'm trying to reverse the following code in order to provide a function which takes the buffer and decrypts it. void crypt_buffer(unsigned char *buffer, size_t size, char *key) { size_t i; int j; j = 0; for(i = 0; i < size; i++) { if(j >= KEY_SIZE) j = 0;...

Text justification C language


c,text,alignment
I have to solve a problem that involves left justification string length and leading zeros. I have the following table : BEGIN CLOSE CONCATENATE DELETE END INITIALIZE PRINT WRITE This is produced by a simple program. My problem is to find out how to convert it like that : It...

Galois LFSR - how to specify the output bit number


c,prng,shift-register
I am trying to understand how change the galois LFSR code to be able to specify the output bit number as a parameter for the function mentioned below. I mean I need to return not the last bit of LFSR as output bit, but any bit of the LFSR (...

How to read string until two consecutive spaces?


c,format,sscanf,c-strings
A well known function of the scanf() functions is that you can pass a format to scan input according to this format. For my case, I cannot seem to find a solution searching this and this documentation. I have a string (sInput) as the following: #something VAR1 this is a...

Infinite loop with fread


c,arrays,loops,malloc,fread
I'm trying to allocate an array 64 bytes in size and then loop over the array indexes to put a read a byte each from the inputfile. but when I don't malloc() the array indexes, the loop stays in index0 (so each time it loops it replaces the content in...

OpenGL glTexImage2D memory issue


c,opengl
I'm loading a cubemap to create a skybox, everything is fine and the skybox renders properly with a correct texture application. However, I decided to check my program safety with valgrind, Valgrind gives this error: http://pastebin.com/seqmXjyx The line 53 in sky.c is: glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, texture.width, texture.height, 0,...

C programming - Confusion regarding curly braces


c,scope
The following code is for replacing multiple consecutive spaces into 1 space. Although I manage to do it, I am confused in the use of curly braces. This one is actually running fine: #include <stdio.h> #include <stdlib.h> int main() { int ch, lastch; lastch = 'a'; while((ch = getchar())!= EOF)...

Call template function for the value of a pointer out of a template function, in C++


c++,templates,pointers,c++11
I am trying to call a template function for the pointer that was given as template parameter in my calling function. My code is: template <> struct serialize_helper<std::string> { // not important code... } }; template <class T> inline void serializer(const T& obj, StreamType::iterator& res) { if(std::is_pointer<T>::value) { //THIS doesn'...

C language, vector of struct, miss something?


c,vector,struct
This is a part of my program that I want to create a vector of struct typedef struct { char nome[501]; int qtd; int linha; int coluna; } tPeca; tPeca* criarPecas(FILE *pFile, int tam) { int i; tPeca *pecaJogo = (tPeca*)malloc(tam*sizeof(tPeca)); if (pecaJogo == NULL) return NULL; for (i =...

Parameters to use in a referenced function c++


c++,pointers,reference
I am very confused as to what kind of variables I would put into my function here: names. I am doing a practice problem in a C++ book, because I am learning C++ and am on References and pointers right now, and cannot find a solution. Just for background information,...

Efficient comparison of small integer vectors


c,integer,compare,bit-manipulation,string-comparison
I have small vectors. Each of them is made of 10 integers which are between 0 and 15. This means that every element in a vector can be written using 4 bits. Hence I can concatenate my vector elements and store the whole vector in a single long type (in...

How to control C Macro Precedence


c,macros
#define VAL1CHK 20 #define NUM 1 #define JOIN(A,B,C) A##B##C int x = JOIN(VAL,NUM,CHK); With above code my expectation was int x = 20; But i get compilation error as macro expands to int x = VALNUMCHK; // Which is undefined How to make it so that NUM is replaced first...

pointer to pointer dynamic array in C++


c++,arrays,pointers
I've been having bad luck with dynamic pointers when I want to close it. why the application wrote to memory after end of heap buffer? how can I close my array? int main() { . . int **W; W = new int* [n]; for (int i=1; i <= n; i++)...

Disadvantages of calling realloc in a loop


c,memory-management,out-of-memory,realloc
I'm trying to implement some math algorithms in C on Windows 7, and I need to repeatedly increase size of my array. Sometimes it fails because realloc can't allocate memory. But if I allocate a lot of memory at once in the beginning it works fine. Is it a problem...

Is post-increment operator guaranteed to run instantly?


c,c89,post-increment,ansi-c
Let's say I have the following code: int i = 0; func(i++, i++); The increment is happening right after returning the value? Is it guaranteed that the first argument will be 0, and the second argument will be 1?...

How can I align stack to the end of SRAM?


c,embedded,stm32,gnu-arm,coocox
I have a STM32F103VCT6 microcontroller with 48kb of SRAM, and recently i've got a memory collision: I have some static variable (lets call it A) located in heap with size of 0x7000 and I wrote some simple function to get info about stack and heap: void check(int depth) { char...

Set precision dynamically using sprintf


c,printf,format-string
Using sprintf and the general syntax "%A.B" I can do this: double a = 0.0000005l; char myNumber[50]; sprintf(myNumber,"%.2lf",a); Can I set A and B dynamically in the format string?...

How does ((a++,b)) work? [duplicate]


c,function,recursion,comma
This question already has an answer here: What does the comma operator `,` do in C? 8 answers In the below block of code, I am trying to understand how the line return reverse((i++, i)) is working. #include <stdio.h> void reverse(int i); int main() { reverse(1); } void reverse(int...

Counting bytes received by posix read()


c,function,serial-port,posix
I get confused with one line of code: temp_uart_count = read(VCOM, temp_uart_data, 4096); I found more about read function at http://linux.die.net/man/3/read, but if everything is okay it returns 0, so how we can get num of bytes received from that? temp_uart_count is used to count how much bytes we received...

How convert unsigned int to unsigned char array


c++,c
I just need to extract those bytes using bitwise & operator. 0xFF is a hexadecimal mask to extract one byte. For 2 bytes, this code is working correctly: #include <stdio.h> int main() { unsigned int i = 0x7ee; unsigned char c[2]; c[0] = i & 0xFF; c[1] = (i>>8) &...

Loop through database table and compare user input


mysql,c
I am trying to loop through the rows in a MySql table and compare the data in a certain column to some user input using C. Currently my code looks like this: MYSQL *cxn = mysql_init(NULL); MYSQL_RES *result; unsigned int num_fields; unsigned int num_rows; char *query_string; MYSQL_ROW *row; if (mysql_real_connect(cxn,...

double* android ndk crash


c++,pointers,android-ndk
I'm facing a peculiar problem with the android ndk. I'm trying to read a previously stored set of bytes in an unsigned char* readBytes (previous allocated and read from file). The data needs to be interpreted as double. unsigned char* svDataOffset=(unsigned char*)(readBytes+byteCounter); unsigned char* chars=(unsigned char*)(svDataOffset+2); //offset of 2 is...

Segmentation Fault if I don't say int i=0


c,arrays,segmentation-fault,initialization,int
void removeVowels(char* array){ int i,j,v; i=0; char vowel[]={'a','e','i','o','u'}; while(array[i]!='\0') { for(v=0;v<5;v++) { if (array[i]==vowel[v]) { j=i; while(array[j]!='\0') { array[j]=array[j+1]; j++; } i--; break; } } i++; } } in function removeVowels() if I don't include i=0; and just say int i; why does it give segmentation fault? Isn't it automatically...

Is there Predefined-Macros define about byte order in armcc


c,armcc,predefined-macro
Is there Predefined-Macros define about byte order in armcc. I am a novice on the armcc.and sorry for my English. In gcc these are macros: __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__ __ORDER_BIG_ENDIAN__ __ORDER_PDP_ENDIAN__ ... Now I have to use armcc, Is there same like these with armcc? Thank a lot. by the way,the armcc...

Passing int using char pointer in C


c,exec,ipc
I'm trying to figure out how to pass an int using a char pointer. It fails once the int value is too large for the char. This is what I'm trying to figure out: char *args[5]; int i = 20; /*some other code/assignments*/ args[2] = (char *)&i; execv(path, args); How...

Program to reverse a string in C without declaring a char[]


c,string,pointers,char
I need to reverse a given string and display it without using the value At[index] notation , I tried the below program using pointers,but it does not print anything for the reverse string, Please help! int main() { char* name=malloc(256); printf("\nEnter string\n"); scanf("%s",name); printf("\nYou entered%s",name); int i,count; count=0; //find the...

memory content not erased after deleting my pointer (on a simple example) [duplicate]


c++,pointers,memory-management
This question already has an answer here: Can a local variable's memory be accessed outside its scope? 16 answers Here is a simple of example of a question I have: I create a pointer of integer (value 5), I print the pointer (hence the address) of the memory case...

VS2012 Identifer not found when part of static lib


c,visual-studio-2012,linker,static-libraries
Using VS2012 C/C++: I created and linked a static lib called "libtools" to my project. Calls to functions in the libtools lib worked as expected. I created and linked a second static lib called "shunt" to my project. But when I incorporate a call to a function in shunt, I...

How does this code print odd and even?


c,if-statement,macros,logic
#define MACRO(num, str) {\ printf("%d", num);\ printf(" is");\ printf(" %s number", str);\ printf("\n");\ } int main(void) { int num; printf("Enter a number: "); scanf("%d", &num); if (num & 1) { MACRO(num, "Odd"); } else { MACRO(num, "Even"); } return 0; } Please explain the above code (if/else condition and how...

Can assignment from a const_iterator dereference cause undefined behaviour?


c++,pointers,pass-by-reference,undefined-behavior,const-iterator
This code is a simplified test for something I am trying to do for real elsewhere. I have a function which takes a "ref-to-ptr" argument and modifies it to return a pointer from a list of pointers. #include <iostream> #include <list> using namespace std; typedef int* intp; typedef std::list<intp> intplist;...