简体   繁体   中英

C Programming - Sprintf & String Arrays

I've been reading a few other questions from folks on arrays of strings. I drew some insight and changed my code, but one problem I'm having is incorporating sprintf.

High level, the purpose of this will ultimately be a function to fopen/fread a variable number of files in a directory. But getting hung up on this string manipulation portion.

I'd like to increment my pointers within sprintf, but I'm getting segmentation issues. Any thoughts on fixing what I have or perhaps a different route? MAX = 20, FILES = 4.

char fName_A[MAX];
char fName_B[MAX];
char * ptr_A[FILES];
char * ptr_B[FILES];
int i;

for(i=0; i<FILES; i++){
    sprintf(fName_A, "waveA00%d.bin", i);
    sprintf(fName_B, "waveB00%d.bin", i);

    ptr_A[i] = fName_A;
    ptr_B[i] = fName_B;

    printf("Ch1 File Number %d is named %s\n", i, *(ptr_A+i));
    printf("Ch2 File Number %d is named %s\n", i, *(ptr_B+i));
}

printf("fName_A[0] = %s\n", *ptr_A);
printf("fName_A[1] = %s\n", *(ptr_A + 1));
printf("fName_A[2] = %s\n", *(ptr_A + 2));
printf("fName_A[3] = %s\n", *(ptr_A + 3));

return 0;

You are not allocating any memory for strings associated with Ptr_A and Ptr_B, just setting the pointers to point to the buffers fName_A and fName_B, so when you check at the end, they all point to the last string stored in these buffers.

Fix it by allocating store for each filename in A and B as an array of chars, instead of using pointers. Here's an example:

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

#define MAX   100
#define FILES 4

int main(int argc, char** argv)
{
 char fName_A[MAX];
 char fName_B[MAX];
 char A[FILES][MAX];
 char B[FILES][MAX];
 int i;

 for(i=0; i<FILES; i++){
    sprintf(fName_A, "waveA00%d.bin", i);
    sprintf(fName_B, "waveB00%d.bin", i);

    strcpy(A[i], fName_A);
    strcpy(B[i], fName_B);

    printf("Ch1 File Number %d is named %s\n", i, A[i]);
    printf("Ch2 File Number %d is named %s\n", i, B[i]);
 }

 for(i=0; i<FILES; i++) {
    printf("A[%d] = %s\n", i, A[i]);
    printf("B[%d] = %s\n", i, B[i]);
 }
}

This will output the following:

Ch1 File Number 0 is named waveA000.bin
Ch2 File Number 0 is named waveB000.bin
Ch1 File Number 1 is named waveA001.bin
Ch2 File Number 1 is named waveB001.bin
Ch1 File Number 2 is named waveA002.bin
Ch2 File Number 2 is named waveB002.bin
Ch1 File Number 3 is named waveA003.bin
Ch2 File Number 3 is named waveB003.bin
A[0] = waveA000.bin
B[0] = waveB000.bin
A[1] = waveA001.bin
B[1] = waveB001.bin
A[2] = waveA002.bin
B[2] = waveB002.bin
A[3] = waveA003.bin
B[3] = waveB003.bin

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM