Can someone please tell me what is wrong with strcmp? I don't understand why I am getting a segmentation fault when comparing array of strings and string.

    char *strings[100];
    char nam[100];
    int g = 0;
    while (fscanf(pFile, "%s %d",  nam, &val) !=EOF)
    {

        strings[k] = nam;
        printf(" string is %s .\n", strings[k]);
        k++;
        g = strcmp (strings[i], nam);
        printf("g is %d \n", g);
    }

Recommended Answers

All 3 Replies

Is this the whole code?
k and i are not defined and initialized.
Do you want to compare all read strings with the actual one?

Line 1: strings is not an array of strings it is an array of pointer to char which means...

Line 7: All the entries in strings are pointed to the same buffer, nam

Also k @ lines 7/8 and i @ line 10 are not mentioned anywhere else so we can't tell what value they have and if it is correct.

Assuming k has a good value then if line 9 came after line 10 the code at line 10 could use k too.

val @ line 4 is also not defined anywhere, when posting code it is important to make sure that everything you have posted is defined, and for preference you should post code that can just be copied out of the site into a text file and compiled.

This code works under GNU GCC version 4.7.2 and returns 0 for g:

#include <stdio.h>
#include <string.h>
int main(void)
{
char *strings[100];
char nam[100] = "test";
int g = 0;    
strings[0] = "test";
g = strcmp (strings[0], nam);
printf("g is %d \n", g);
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.